<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><div id="myscoll"></div><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>第十三-MySQL约束 | XiaoFei🥝</title><meta name="keywords" content="第十三-MySQL约束"><meta name="author" content="XiaoFei🥝"><meta name="copyright" content="XiaoFei🥝"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="第十三-MySQL约束">
<meta property="og:type" content="article">
<meta property="og:title" content="第十三-MySQL约束">
<meta property="og:url" content="https://www.naste.top:1024/posts/986000951.html">
<meta property="og:site_name" content="XiaoFei🥝">
<meta property="og:description" content="第十三-MySQL约束">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://www.naste.top:9000/webp/1675912188.webp">
<meta property="article:published_time" content="2022-09-19T09:56:49.000Z">
<meta property="article:modified_time" content="2024-04-26T09:52:18.891Z">
<meta property="article:author" content="XiaoFei🥝">
<meta property="article:tag" content="MySQL">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://www.naste.top:9000/webp/1675912188.webp"><link rel="shortcut icon" href="/"><link rel="canonical" href="https://www.naste.top:1024/posts/986000951"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/font-awesome/6.0.0/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.staticfile.org/fancyapps-ui/4.0.31/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.json","preload":true,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: {"limitDay":365,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":230},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdnjs.cloudflare.com/ajax/libs/flickr-justified-gallery/2.1.2/fjGallery.min.js',
      css: 'https://cdnjs.cloudflare.com/ajax/libs/flickr-justified-gallery/2.1.2/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '第十三-MySQL约束',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-04-26 17:52:18'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="https://cdn1.tianli0.top/npm/element-ui@2.15.6/packages/theme-chalk/lib/index.css"><style id="themeColor"></style><style id="rightSide"></style><style id="transPercent"></style><style id="blurNum"></style><style id="settingStyle"></style><span id="fps"></span><style id="defineBg"></style><style id="menu_shadow"></style><svg aria-hidden="true" style="position:absolute; overflow:hidden; width:0; height:0"><symbol id="icon-sun" viewBox="0 0 1024 1024"><path d="M960 512l-128 128v192h-192l-128 128-128-128H192v-192l-128-128 128-128V192h192l128-128 128 128h192v192z" fill="#FFD878" p-id="8420"></path><path d="M736 512a224 224 0 1 0-448 0 224 224 0 1 0 448 0z" fill="#FFE4A9" p-id="8421"></path><path d="M512 109.248L626.752 224H800v173.248L914.752 512 800 626.752V800h-173.248L512 914.752 397.248 800H224v-173.248L109.248 512 224 397.248V224h173.248L512 109.248M512 64l-128 128H192v192l-128 128 128 128v192h192l128 128 128-128h192v-192l128-128-128-128V192h-192l-128-128z" fill="#4D5152" p-id="8422"></path><path d="M512 320c105.888 0 192 86.112 192 192s-86.112 192-192 192-192-86.112-192-192 86.112-192 192-192m0-32a224 224 0 1 0 0 448 224 224 0 0 0 0-448z" fill="#4D5152" p-id="8423"></path></symbol><symbol id="icon-moon" viewBox="0 0 1024 1024"><path d="M611.370667 167.082667a445.013333 445.013333 0 0 1-38.4 161.834666 477.824 477.824 0 0 1-244.736 244.394667 445.141333 445.141333 0 0 1-161.109334 38.058667 85.077333 85.077333 0 0 0-65.066666 135.722666A462.08 462.08 0 1 0 747.093333 102.058667a85.077333 85.077333 0 0 0-135.722666 65.024z" fill="#FFB531" p-id="11345"></path><path d="M329.728 274.133333l35.157333-35.157333a21.333333 21.333333 0 1 0-30.165333-30.165333l-35.157333 35.157333-35.114667-35.157333a21.333333 21.333333 0 0 0-30.165333 30.165333l35.114666 35.157333-35.114666 35.157334a21.333333 21.333333 0 1 0 30.165333 30.165333l35.114667-35.157333 35.157333 35.157333a21.333333 21.333333 0 1 0 30.165333-30.165333z" fill="#030835" p-id="11346"></path></symbol></svg><!-- hexo injector head_end start --><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiperstyle.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/assets/font-awesome-animation.min.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/tag_plugins.css" media="defer" onload="this.media='all'"><script src="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/assets/carousel-touch.js"></script><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/animate.min.css" media="print" onload="this.media='screen'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-filter-gitcalendar/lib/gitcalendar.css" media="print" onload="this.media='all'"><!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.3.0"><link rel="alternate" href="/atom.xml" title="XiaoFei🥝" type="application/atom+xml">
</head><body><div id="loading-box" onclick="document.getElementById(&quot;loading-box&quot;).classList.add(&quot;loaded&quot;)"><div class="loading-bg"><div class="loading-img"></div><div class="loading-image-dot"></div></div></div><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://www.naste.top:9000/images/cat.jpg" onerror="onerror=null;src='/assets/r1.jpg'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">149</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">99</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">46</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-home"></use></svg><span class="menu_word" style="font-size:17px"> 首页</span></a></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon--article"></use></svg><span class="menu_word" style="font-size:17px"> 文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/archives/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-guidang1">                   </use></svg><span class="menu_word" style="font-size:17px"> 归档</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/tags/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-sekuaibiaoqian">                   </use></svg><span class="menu_word" style="font-size:17px"> 标签</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/categories/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-fenlei">                   </use></svg><span class="menu_word" style="font-size:17px"> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-pinweishenghuo"></use></svg><span class="menu_word" style="font-size:17px"> 休闲</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/life/music/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-yinle">                   </use></svg><span class="menu_word" style="font-size:17px"> 八音盒</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/life/movies/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-dianying1">                   </use></svg><span class="menu_word" style="font-size:17px"> 影院</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/life/games/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-youxishoubing">                   </use></svg><span class="menu_word" style="font-size:17px"> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-xiangzi"></use></svg><span class="menu_word" style="font-size:17px"> 八宝箱</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/box/gallery/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-tubiaozhizuomoban">                   </use></svg><span class="menu_word" style="font-size:17px"> 画廊</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/box/animation/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-nvwumao">                   </use></svg><span class="menu_word" style="font-size:17px"> 动画</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/box/nav/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-zhifengche">                   </use></svg><span class="menu_word" style="font-size:17px"> 网址导航</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-shejiaoxinxi"></use></svg><span class="menu_word" style="font-size:17px"> 社交</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/social/fcircle/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-pengyouquan">                   </use></svg><span class="menu_word" style="font-size:17px"> 朋友圈</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/comments/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-liuyan">                   </use></svg><span class="menu_word" style="font-size:17px"> 留言板</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/social/link/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-lianjie">                   </use></svg><span class="menu_word" style="font-size:17px"> 友人帐</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-wangye"></use></svg><span class="menu_word" style="font-size:17px"> 网站</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/site/census/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon--tongjibiao">                   </use></svg><span class="menu_word" style="font-size:17px"> 网站统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/site/echarts/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-shujutongji1">                   </use></svg><span class="menu_word" style="font-size:17px"> 文章统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/site/time/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-xianxingshalou">                   </use></svg><span class="menu_word" style="font-size:17px"> 旧时光</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-maoliang"></use></svg><span class="menu_word" style="font-size:17px"> 个人</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/personal/bb/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-qunliaotian">                   </use></svg><span class="menu_word" style="font-size:17px"> 唠叨</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/personal/love/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-love-sign">                   </use></svg><span class="menu_word" style="font-size:17px"> 恋爱小屋</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/personal/about/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-paperplane">                   </use></svg><span class="menu_word" style="font-size:17px"> 关于</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/encryption/%E6%9C%BA%E5%9C%BA/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-paperplane">                   </use></svg><span class="menu_word" style="font-size:17px"> 机场</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">XiaoFei🥝</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-home"></use></svg><span class="menu_word" style="font-size:17px"> 首页</span></a></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon--article"></use></svg><span class="menu_word" style="font-size:17px"> 文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/archives/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-guidang1">                   </use></svg><span class="menu_word" style="font-size:17px"> 归档</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/tags/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-sekuaibiaoqian">                   </use></svg><span class="menu_word" style="font-size:17px"> 标签</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/categories/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-fenlei">                   </use></svg><span class="menu_word" style="font-size:17px"> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-pinweishenghuo"></use></svg><span class="menu_word" style="font-size:17px"> 休闲</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/life/music/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-yinle">                   </use></svg><span class="menu_word" style="font-size:17px"> 八音盒</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/life/movies/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-dianying1">                   </use></svg><span class="menu_word" style="font-size:17px"> 影院</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/life/games/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-youxishoubing">                   </use></svg><span class="menu_word" style="font-size:17px"> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-xiangzi"></use></svg><span class="menu_word" style="font-size:17px"> 八宝箱</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/box/gallery/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-tubiaozhizuomoban">                   </use></svg><span class="menu_word" style="font-size:17px"> 画廊</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/box/animation/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-nvwumao">                   </use></svg><span class="menu_word" style="font-size:17px"> 动画</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/box/nav/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-zhifengche">                   </use></svg><span class="menu_word" style="font-size:17px"> 网址导航</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-shejiaoxinxi"></use></svg><span class="menu_word" style="font-size:17px"> 社交</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/social/fcircle/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-pengyouquan">                   </use></svg><span class="menu_word" style="font-size:17px"> 朋友圈</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/comments/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-liuyan">                   </use></svg><span class="menu_word" style="font-size:17px"> 留言板</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/social/link/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-lianjie">                   </use></svg><span class="menu_word" style="font-size:17px"> 友人帐</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-wangye"></use></svg><span class="menu_word" style="font-size:17px"> 网站</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/site/census/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon--tongjibiao">                   </use></svg><span class="menu_word" style="font-size:17px"> 网站统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/site/echarts/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-shujutongji1">                   </use></svg><span class="menu_word" style="font-size:17px"> 文章统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/site/time/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-xianxingshalou">                   </use></svg><span class="menu_word" style="font-size:17px"> 旧时光</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-maoliang"></use></svg><span class="menu_word" style="font-size:17px"> 个人</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/personal/bb/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-qunliaotian">                   </use></svg><span class="menu_word" style="font-size:17px"> 唠叨</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/personal/love/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-love-sign">                   </use></svg><span class="menu_word" style="font-size:17px"> 恋爱小屋</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/personal/about/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-paperplane">                   </use></svg><span class="menu_word" style="font-size:17px"> 关于</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/encryption/%E6%9C%BA%E5%9C%BA/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-paperplane">                   </use></svg><span class="menu_word" style="font-size:17px"> 机场</span></a></li></ul></div></div><center id="name-container"><a id="page-name" href="javascript:scrollToTop()">PAGE_NAME</a></center><div id="nav-right"><div id="search-button"><a class="search faa-parent animated-hover" title="检索站内任何你想要的信息"><svg class="faa-tada icon" style="height:24px;width:24px;fill:currentColor;position:relative;top:6px" aria-hidden="true"><use xlink:href="#icon-valentine_-search-love-find-heart"></use></svg><span> 搜索</span></a></div><a class="meihua faa-parent animated-hover" onclick="toggleWinbox()" title="美化设置-自定义你的风格" id="meihua-button"><svg class="faa-tada icon" style="height:26px;width:26px;fill:currentColor;position:relative;top:8px" aria-hidden="true"><use xlink:href="#icon-tupian1"></use></svg></a><a class="sun_moon faa-parent animated-hover" onclick="switchNightMode()" title="浅色和深色模式转换" id="nightmode-button"><svg class="faa-tada" style="height:25px;width:25px;fill:currentColor;position:relative;top:7px" viewBox="0 0 1024 1024"><use id="modeicon" xlink:href="#icon-moon">       </use></svg></a><div id="toggle-menu"><a><i class="fas fa-bars fa-fw"></i></a></div></div></div></nav><div id="post-info"><h1 class="post-title">第十三-MySQL约束</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><svg class="meta_icon post-meta-icon" style="width:30px;height:30px;position:relative;top:10px"><use xlink:href="#icon-rili"></use></svg><span class="post-meta-label">发表于 </span><time class="post-meta-date-created" datetime="2022-09-19T09:56:49.000Z" title="发表于 2022-09-19 17:56:49">2022-09-19</time><span class="post-meta-separator">|</span><svg class="meta_icon post-meta-icon" style="width:18px;height:18px;position:relative;top:5px"><use xlink:href="#icon-gengxin1"></use></svg><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-04-26T09:52:18.891Z" title="更新于 2024-04-26 17:52:18">2024-04-26</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><svg class="meta_icon post-meta-icon" style="width:18px;height:18px;position:relative;top:5px"><use xlink:href="#icon-biaoqian"></use></svg><a class="post-meta-categories" href="/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/">中间件</a><i class="fas fa-angle-right post-meta-separator"></i><svg class="meta_icon post-meta-icon" style="width:18px;height:18px;position:relative;top:5px"><use xlink:href="#icon-biaoqian"></use></svg><a class="post-meta-categories" href="/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/MySQL/">MySQL</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><svg class="meta_icon post-meta-icon" style="width:25px;height:25px;position:relative;top:8px"><use xlink:href="#icon-charuword"></use></svg><span class="post-meta-label">字数总计:</span><span class="word-count">1w</span><span class="post-meta-separator">|</span><svg class="meta_icon post-meta-icon" style="width:20px;height:20px;position:relative;top:5px"><use xlink:href="#icon-shizhong"></use></svg><span class="post-meta-label">阅读时长:</span><span>41分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="第十三-MySQL约束"><svg class="meta_icon post-meta-icon" style="width:25px;height:25px;position:relative;top:5px"><use xlink:href="#icon-eye"></use></svg><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div><section class="main-hero-waves-area waves-area"><svg class="waves-svg" xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink" viewBox="0 24 150 28" preserveAspectRatio="none" shape-rendering="auto"><defs><path id="gentle-wave" d="M -160 44 c 30 0 58 -18 88 -18 s 58 18 88 18 s 58 -18 88 -18 s 58 18 88 18 v 44 h -352 Z"></path></defs><g class="parallax"><use href="#gentle-wave" x="48" y="0"></use><use href="#gentle-wave" x="48" y="3"></use><use href="#gentle-wave" x="48" y="5"></use><use href="#gentle-wave" x="48" y="7"></use></g></svg></section></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="第13章-约束"><a href="#第13章-约束" class="headerlink" title="第13章_约束"></a>第13章_约束</h1><h2 id="1-约束-constraint-概述"><a href="#1-约束-constraint-概述" class="headerlink" title="1. 约束(constraint)概述"></a>1. 约束(constraint)概述</h2><h3 id="1-1-为什么需要约束"><a href="#1-1-为什么需要约束" class="headerlink" title="1.1 为什么需要约束"></a>1.1 为什么需要约束</h3><p>数据完整性（Data Integrity）是指数据的精确性（Accuracy）和可靠性（Reliability）。它是防止数据库中存在不符合语义规定的数据和防止因错误信息的输入输出造成无效操作或错误信息而提出的。</p>
<p>为了保证数据的完整性，SQL规范以约束的方式对<strong>表数据进行额外的条件限制</strong>。从以下四个方面考虑：</p>
<ul>
<li><code>实体完整性（Entity Integrity）</code>：例如，同一个表中，不能存在两条完全相同无法区分的记录</li>
<li><code>域完整性（Domain Integrity）</code>：例如：年龄范围0-120，性别范围“男/女”</li>
<li><code>引用完整性（Referential Integrity）</code>：例如：员工所在部门，在部门表中要能找到这个部门</li>
<li><code>用户自定义完整性（User-defined Integrity）</code>：例如：用户名唯一、密码不能为空等，本部门经理的工资不得高于本部门职工的平均工资的5倍。</li>
</ul>
<h3 id="1-2-什么是约束"><a href="#1-2-什么是约束" class="headerlink" title="1.2 什么是约束"></a>1.2 什么是约束</h3><p>约束是表级的强制规定。</p>
<p>可以在<strong>创建表时规定约束（通过 CREATE TABLE 语句）</strong>，或者在<strong>表创建之后通过 ALTER TABLE 语句规定约束</strong>。</p>
<h3 id="1-3-约束的分类"><a href="#1-3-约束的分类" class="headerlink" title="1.3 约束的分类"></a>1.3 约束的分类</h3><ul>
<li><strong>根据约束数据列的限制，</strong>约束可分为：<ul>
<li><strong>单列约束</strong>：每个约束只约束一列</li>
<li><strong>多列约束</strong>：每个约束可约束多列数据</li>
</ul>
</li>
<li><strong>根据约束的作用范围</strong>，约束可分为：<ul>
<li><strong>列级约束</strong>：只能作用在一个列上，跟在列的定义后面</li>
<li><strong>表级约束</strong>：可以作用在多个列上，不与列一起，而是单独定义</li>
</ul>
</li>
</ul>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">			位置			支持的约束类型					是否可以起约束名</span><br><span class="line">列级约束：	列的后面		语法都支持，但外键没有效果		不可以</span><br><span class="line">表级约束：	所有列的下面	   默认和非空不支持，其他支持	   可以（主键没有效果）</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>根据约束起的作用</strong>，约束可分为：<ul>
<li><strong>NOT NULL</strong> <strong>非空约束，规定某个字段不能为空</strong></li>
<li><strong>UNIQUE</strong>  <strong>唯一约束</strong>，<strong>规定某个字段在整个表中是唯一的</strong></li>
<li><strong>PRIMARY KEY  主键(非空且唯一)约束</strong></li>
<li><strong>FOREIGN KEY</strong>  <strong>外键约束</strong></li>
<li><strong>CHECK</strong>  <strong>检查约束</strong></li>
<li><strong>DEFAULT</strong>  <strong>默认值约束</strong></li>
</ul>
</li>
</ul>
<blockquote>
<p>注意： MySQL不支持check约束，但可以使用check约束，而没有任何效果</p>
</blockquote>
<ul>
<li>查看某个表已有的约束</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">#information_schema数据库名（系统库）</span><br><span class="line">#table_constraints表名称（专门存储各个表的约束）</span><br><span class="line">SELECT * FROM information_schema.table_constraints </span><br><span class="line">WHERE table_name = &#x27;表名称&#x27;;</span><br></pre></td></tr></table></figure>
<h2 id="2-非空约束"><a href="#2-非空约束" class="headerlink" title="2. 非空约束"></a>2. 非空约束</h2><h3 id="2-1-作用"><a href="#2-1-作用" class="headerlink" title="2.1 作用"></a>2.1 作用</h3><p>限定某个字段/某列的值不允许为空</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1555426972098.webp" alt="1555426972098"></p>
<h3 id="2-2-关键字"><a href="#2-2-关键字" class="headerlink" title="2.2 关键字"></a>2.2 关键字</h3><p>NOT NULL</p>
<h3 id="2-3-特点"><a href="#2-3-特点" class="headerlink" title="2.3 特点"></a>2.3 特点</h3><ul>
<li>默认，所有的类型的值都可以是NULL，包括INT、FLOAT等数据类型</li>
<li><p>非空约束只能出现在表对象的列上，只能某个列单独限定非空，不能组合非空</p>
</li>
<li><p>一个表可以有很多列都分别限定了非空</p>
</li>
<li><p>空字符串’’不等于NULL，0也不等于NULL</p>
</li>
</ul>
<h3 id="2-4-添加非空约束"><a href="#2-4-添加非空约束" class="headerlink" title="2.4 添加非空约束"></a>2.4 添加非空约束</h3><p>（1）建表时</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE 表名称(</span><br><span class="line">	字段名  数据类型,</span><br><span class="line">    字段名  数据类型 NOT NULL,  </span><br><span class="line">    字段名  数据类型 NOT NULL</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<p>举例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE emp(</span><br><span class="line">id INT(10) NOT NULL,</span><br><span class="line">NAME VARCHAR(20) NOT NULL,</span><br><span class="line">sex CHAR NULL</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE student(</span><br><span class="line">	sid int,</span><br><span class="line">    sname varchar(20) not null,</span><br><span class="line">    tel char(11) ,</span><br><span class="line">    cardid char(18) not null</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">insert into student values(1,&#x27;张三&#x27;,&#x27;13710011002&#x27;,&#x27;110222198912032545&#x27;); #成功</span><br><span class="line"></span><br><span class="line">insert into student values(2,&#x27;李四&#x27;,&#x27;13710011002&#x27;,null);#身份证号为空</span><br><span class="line">ERROR 1048 (23000): Column &#x27;cardid&#x27; cannot be null</span><br><span class="line"></span><br><span class="line">insert into student values(2,&#x27;李四&#x27;,null,&#x27;110222198912032546&#x27;);#成功，tel允许为空</span><br><span class="line"></span><br><span class="line">insert into student values(3,null,null,&#x27;110222198912032547&#x27;);#失败</span><br><span class="line">ERROR 1048 (23000): Column &#x27;sname&#x27; cannot be null</span><br></pre></td></tr></table></figure>
<p>（2）建表后</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alter table 表名称 modify 字段名 数据类型 not null;</span><br></pre></td></tr></table></figure>
<p>举例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ALTER TABLE emp</span><br><span class="line">MODIFY sex VARCHAR(30) NOT NULL;</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alter table student modify sname varchar(20) not null;</span><br></pre></td></tr></table></figure>
<h3 id="2-5-删除非空约束"><a href="#2-5-删除非空约束" class="headerlink" title="2.5 删除非空约束"></a>2.5 删除非空约束</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">alter table 表名称 modify 字段名 数据类型 NULL;#去掉not null，相当于修改某个非注解字段，该字段允许为空</span><br><span class="line"></span><br><span class="line">或 </span><br><span class="line"></span><br><span class="line">alter table 表名称 modify 字段名 数据类型;#去掉not null，相当于修改某个非注解字段，该字段允许为空</span><br></pre></td></tr></table></figure>
<p>举例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ALTER TABLE emp</span><br><span class="line">MODIFY sex VARCHAR(30) NULL;</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ALTER TABLE emp</span><br><span class="line">MODIFY NAME VARCHAR(15) DEFAULT &#x27;abc&#x27; NULL;</span><br></pre></td></tr></table></figure>
<h2 id="3-唯一性约束"><a href="#3-唯一性约束" class="headerlink" title="3. 唯一性约束"></a>3. 唯一性约束</h2><h3 id="3-1-作用"><a href="#3-1-作用" class="headerlink" title="3.1 作用"></a>3.1 作用</h3><p>用来限制某个字段/某列的值不能重复。</p>
<p> <img src= "" data-lazy-src="https://www.naste.top:9000/webp/1555427198811.webp" alt="1555427198811"></p>
<h3 id="3-2-关键字"><a href="#3-2-关键字" class="headerlink" title="3.2 关键字"></a>3.2 关键字</h3><p>UNIQUE</p>
<h3 id="3-3-特点"><a href="#3-3-特点" class="headerlink" title="3.3 特点"></a>3.3 特点</h3><ul>
<li>同一个表可以有多个唯一约束。</li>
<li>唯一约束可以是某一个列的值唯一，也可以多个列组合的值唯一。</li>
<li>唯一性约束允许列值为空。</li>
<li>在创建唯一约束的时候，如果不给唯一约束命名，就默认和列名相同。</li>
<li><strong>MySQL会给唯一约束的列上默认创建一个唯一索引。</strong></li>
</ul>
<h3 id="3-4-添加唯一约束"><a href="#3-4-添加唯一约束" class="headerlink" title="3.4 添加唯一约束"></a>3.4 添加唯一约束</h3><p>（1）建表时</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">create table 表名称(</span><br><span class="line">	字段名  数据类型,</span><br><span class="line">    字段名  数据类型  unique,  </span><br><span class="line">    字段名  数据类型  unique key,</span><br><span class="line">    字段名  数据类型</span><br><span class="line">);</span><br><span class="line">create table 表名称(</span><br><span class="line">	字段名  数据类型,</span><br><span class="line">    字段名  数据类型,  </span><br><span class="line">    字段名  数据类型,</span><br><span class="line">    [constraint 约束名] unique key(字段名)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<p>举例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">create table student(</span><br><span class="line">	sid int,</span><br><span class="line">    sname varchar(20),</span><br><span class="line">    tel char(11) unique,</span><br><span class="line">    cardid char(18) unique key</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE t_course(</span><br><span class="line">	cid INT UNIQUE,</span><br><span class="line">	cname VARCHAR(100) UNIQUE,</span><br><span class="line">	description VARCHAR(200)</span><br><span class="line">);</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE USER(</span><br><span class="line"> id INT NOT NULL,</span><br><span class="line"> NAME VARCHAR(25),</span><br><span class="line"> PASSWORD VARCHAR(16),</span><br><span class="line"> -- 使用表级约束语法</span><br><span class="line"> CONSTRAINT uk_name_pwd UNIQUE(NAME,PASSWORD)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>表示用户名和密码组合不能重复</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">insert into student values(1,&#x27;张三&#x27;,&#x27;13710011002&#x27;,&#x27;101223199012015623&#x27;);</span><br><span class="line">insert into student values(2,&#x27;李四&#x27;,&#x27;13710011003&#x27;,&#x27;101223199012015624&#x27;);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; select * from student;</span><br><span class="line">+-----+-------+-------------+--------------------+</span><br><span class="line">| sid | sname | tel         | cardid             |</span><br><span class="line">+-----+-------+-------------+--------------------+</span><br><span class="line">|   1 | 张三  | 13710011002 | 101223199012015623 |</span><br><span class="line">|   2 | 李四  | 13710011003 | 101223199012015624 |</span><br><span class="line">+-----+-------+-------------+--------------------+</span><br><span class="line">2 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">insert into student values(3,&#x27;王五&#x27;,&#x27;13710011004&#x27;,&#x27;101223199012015624&#x27;); #身份证号重复</span><br><span class="line">ERROR 1062 (23000): Duplicate entry &#x27;101223199012015624&#x27; for key &#x27;cardid&#x27;</span><br><span class="line"></span><br><span class="line">insert into student values(3,&#x27;王五&#x27;,&#x27;13710011003&#x27;,&#x27;101223199012015625&#x27;); </span><br><span class="line">ERROR 1062 (23000): Duplicate entry &#x27;13710011003&#x27; for key &#x27;tel&#x27;</span><br></pre></td></tr></table></figure>
<p>（2）建表后指定唯一键约束</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">#字段列表中如果是一个字段，表示该列的值唯一。如果是两个或更多个字段，那么复合唯一，即多个字段的组合是唯一的</span><br><span class="line">#方式1：</span><br><span class="line">alter table 表名称 add unique key(字段列表); </span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">#方式2：</span><br><span class="line">alter table 表名称 modify 字段名 字段类型 unique;</span><br></pre></td></tr></table></figure>
<p>举例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ALTER TABLE USER </span><br><span class="line">ADD UNIQUE(NAME,PASSWORD);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ALTER TABLE USER </span><br><span class="line">ADD CONSTRAINT uk_name_pwd UNIQUE(NAME,PASSWORD);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ALTER TABLE USER </span><br><span class="line">MODIFY NAME VARCHAR(20) UNIQUE;</span><br></pre></td></tr></table></figure>
<p>举例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">create table student(</span><br><span class="line">	sid int primary key,</span><br><span class="line">    sname varchar(20),</span><br><span class="line">    tel char(11) ,</span><br><span class="line">    cardid char(18) </span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">alter table student add unique key(tel);</span><br><span class="line">alter table student add unique key(cardid);</span><br></pre></td></tr></table></figure>
<h3 id="3-5-关于复合唯一约束"><a href="#3-5-关于复合唯一约束" class="headerlink" title="3.5 关于复合唯一约束"></a>3.5 关于复合唯一约束</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">create table 表名称(</span><br><span class="line">	字段名  数据类型,</span><br><span class="line">    字段名  数据类型,  </span><br><span class="line">    字段名  数据类型,</span><br><span class="line">    unique key(字段列表) #字段列表中写的是多个字段名，多个字段名用逗号分隔，表示那么是复合唯一，即多个字段的组合是唯一的</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">#学生表</span><br><span class="line">create table student(</span><br><span class="line">	sid int,	#学号</span><br><span class="line">    sname varchar(20),			#姓名</span><br><span class="line">    tel char(11) unique key,  #电话</span><br><span class="line">    cardid char(18) unique key #身份证号</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">#课程表</span><br><span class="line">create table course(</span><br><span class="line">	cid int,  #课程编号</span><br><span class="line">    cname varchar(20)     #课程名称</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">#选课表</span><br><span class="line">create table student_course(</span><br><span class="line">    id int,</span><br><span class="line">	sid int,</span><br><span class="line">    cid int,</span><br><span class="line">    score int,</span><br><span class="line">    unique key(sid,cid)  #复合唯一</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">insert into student values(1,&#x27;张三&#x27;,&#x27;13710011002&#x27;,&#x27;101223199012015623&#x27;);#成功</span><br><span class="line">insert into student values(2,&#x27;李四&#x27;,&#x27;13710011003&#x27;,&#x27;101223199012015624&#x27;);#成功</span><br><span class="line">insert into course values(1001,&#x27;Java&#x27;),(1002,&#x27;MySQL&#x27;);#成功</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; select * from student;</span><br><span class="line">+-----+-------+-------------+--------------------+</span><br><span class="line">| sid | sname | tel         | cardid             |</span><br><span class="line">+-----+-------+-------------+--------------------+</span><br><span class="line">|   1 | 张三  | 13710011002 | 101223199012015623 |</span><br><span class="line">|   2 | 李四  | 13710011003 | 101223199012015624 |</span><br><span class="line">+-----+-------+-------------+--------------------+</span><br><span class="line">2 rows in set (0.00 sec)</span><br><span class="line"></span><br><span class="line">mysql&gt; select * from course;</span><br><span class="line">+------+-------+</span><br><span class="line">| cid  | cname |</span><br><span class="line">+------+-------+</span><br><span class="line">| 1001 | Java  |</span><br><span class="line">| 1002 | MySQL |</span><br><span class="line">+------+-------+</span><br><span class="line">2 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">insert into student_course values</span><br><span class="line">(1, 1, 1001, 89),</span><br><span class="line">(2, 1, 1002, 90),</span><br><span class="line">(3, 2, 1001, 88),</span><br><span class="line">(4, 2, 1002, 56);#成功</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; select * from student_course;</span><br><span class="line">+----+------+------+-------+</span><br><span class="line">| id | sid  | cid  | score |</span><br><span class="line">+----+------+------+-------+</span><br><span class="line">|  1 |    1 | 1001 |    89 |</span><br><span class="line">|  2 |    1 | 1002 |    90 |</span><br><span class="line">|  3 |    2 | 1001 |    88 |</span><br><span class="line">|  4 |    2 | 1002 |    56 |</span><br><span class="line">+----+------+------+-------+</span><br><span class="line">4 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">insert into student_course values (5, 1, 1001, 88);#失败</span><br><span class="line"></span><br><span class="line">#ERROR 1062 (23000): Duplicate entry &#x27;1-1001&#x27; for key &#x27;sid&#x27;   违反sid-cid的复合唯一</span><br></pre></td></tr></table></figure>
<h3 id="3-5-删除唯一约束"><a href="#3-5-删除唯一约束" class="headerlink" title="3.5 删除唯一约束"></a>3.5 删除唯一约束</h3><ul>
<li>添加唯一性约束的列上也会自动创建唯一索引。</li>
<li>删除唯一约束只能通过删除唯一索引的方式删除。</li>
<li>删除时需要指定唯一索引名，唯一索引名就和唯一约束名一样。</li>
<li>如果创建唯一约束时未指定名称，如果是单列，就默认和列名相同；如果是组合列，那么默认和()中排在第一个的列名相同。也可以自定义唯一性约束名。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SELECT * FROM information_schema.table_constraints WHERE table_name = &#x27;表名&#x27;; #查看都有哪些约束</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ALTER TABLE USER </span><br><span class="line">DROP INDEX uk_name_pwd;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>注意：可以通过 <code>show index from 表名称;</code>查看表的索引</p>
</blockquote>
<h2 id="4-PRIMARY-KEY-约束"><a href="#4-PRIMARY-KEY-约束" class="headerlink" title="4. PRIMARY KEY 约束"></a>4. PRIMARY KEY 约束</h2><h3 id="4-1-作用"><a href="#4-1-作用" class="headerlink" title="4.1 作用"></a>4.1 作用</h3><p>用来唯一标识表中的一行记录。</p>
<h3 id="4-2-关键字"><a href="#4-2-关键字" class="headerlink" title="4.2 关键字"></a>4.2 关键字</h3><p>primary key</p>
<h3 id="4-3-特点"><a href="#4-3-特点" class="headerlink" title="4.3 特点"></a>4.3 特点</h3><ul>
<li>主键约束相当于<strong>唯一约束+非空约束的组合</strong>，主键约束列不允许重复，也不允许出现空值。</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1555427492244.webp" alt="1555427492244"></p>
<ul>
<li>一个表最多只能有一个主键约束，建立主键约束可以在列级别创建，也可以在表级别上创建。</li>
</ul>
<ul>
<li>主键约束对应着表中的一列或者多列（复合主键）</li>
<li>如果是多列组合的复合主键约束，那么这些列都不允许为空值，并且组合的值不允许重复。</li>
<li><p><strong>MySQL的主键名总是PRIMARY</strong>，就算自己命名了主键约束名也没用。</p>
</li>
<li><p>当创建主键约束时，系统默认会在所在的列或列组合上建立对应的<strong>主键索引</strong>（能够根据主键查询的，就根据主键查询，效率更高）。如果删除主键约束了，主键约束对应的索引就自动删除了。</p>
</li>
</ul>
<ul>
<li>需要注意的一点是，不要修改主键字段的值。因为主键是数据记录的唯一标识，如果修改了主键的值，就有可能会破坏数据的完整性。</li>
</ul>
<h3 id="4-4-添加主键约束"><a href="#4-4-添加主键约束" class="headerlink" title="4.4 添加主键约束"></a>4.4 添加主键约束</h3><p>（1）建表时指定主键约束</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">create table 表名称(</span><br><span class="line">	字段名  数据类型  primary key, #列级模式</span><br><span class="line">    字段名  数据类型,  </span><br><span class="line">    字段名  数据类型  </span><br><span class="line">);</span><br><span class="line">create table 表名称(</span><br><span class="line">	字段名  数据类型,</span><br><span class="line">    字段名  数据类型,  </span><br><span class="line">    字段名  数据类型,</span><br><span class="line">    [constraint 约束名] primary key(字段名) #表级模式</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<p>举例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">create table temp(</span><br><span class="line">	id int primary key,</span><br><span class="line">    name varchar(20)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; desc temp;</span><br><span class="line">+-------+-------------+------+-----+---------+-------+</span><br><span class="line">| Field | Type        | Null | Key | Default | Extra |</span><br><span class="line">+-------+-------------+------+-----+---------+-------+</span><br><span class="line">| id    | int(11)     | NO   | PRI | NULL    |       |</span><br><span class="line">| name  | varchar(20) | YES  |     | NULL    |       |</span><br><span class="line">+-------+-------------+------+-----+---------+-------+</span><br><span class="line">2 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">insert into temp values(1,&#x27;张三&#x27;);#成功</span><br><span class="line">insert into temp values(2,&#x27;李四&#x27;);#成功</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; select * from temp;</span><br><span class="line">+----+------+</span><br><span class="line">| id | name |</span><br><span class="line">+----+------+</span><br><span class="line">|  1 | 张三 |</span><br><span class="line">|  2 | 李四 |</span><br><span class="line">+----+------+</span><br><span class="line">2 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">insert into temp values(1,&#x27;张三&#x27;);#失败</span><br><span class="line">ERROR 1062 (23000): Duplicate（重复） entry（键入，输入） &#x27;1&#x27; for key &#x27;PRIMARY&#x27;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">insert into temp values(1,&#x27;王五&#x27;);#失败</span><br><span class="line">ERROR 1062 (23000): Duplicate entry &#x27;1&#x27; for key &#x27;PRIMARY&#x27;</span><br><span class="line"></span><br><span class="line">insert into temp values(3,&#x27;张三&#x27;);#成功</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; select * from temp;</span><br><span class="line">+----+------+</span><br><span class="line">| id | name |</span><br><span class="line">+----+------+</span><br><span class="line">|  1 | 张三 |</span><br><span class="line">|  2 | 李四 |</span><br><span class="line">|  3 | 张三 |</span><br><span class="line">+----+------+</span><br><span class="line">3 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">insert into temp values(4,null);#成功</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">insert into temp values(null,&#x27;李琦&#x27;);#失败</span><br><span class="line">ERROR 1048 (23000): Column &#x27;id&#x27; cannot be null</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; select * from temp;</span><br><span class="line">+----+------+</span><br><span class="line">| id | name |</span><br><span class="line">+----+------+</span><br><span class="line">|  1 | 张三 |</span><br><span class="line">|  2 | 李四 |</span><br><span class="line">|  3 | 张三 |</span><br><span class="line">|  4 | NULL |</span><br><span class="line">+----+------+</span><br><span class="line">4 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">#演示一个表建立两个主键约束</span><br><span class="line">create table temp(</span><br><span class="line">	id int primary key,</span><br><span class="line">    name varchar(20) primary key</span><br><span class="line">);</span><br><span class="line">ERROR 1068 (42000): Multiple（多重的） primary key defined（定义）</span><br></pre></td></tr></table></figure>
<p>再举例：</p>
<ul>
<li>列级约束</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE emp4(</span><br><span class="line">id INT PRIMARY KEY AUTO_INCREMENT ,</span><br><span class="line">NAME VARCHAR(20)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<ul>
<li>表级约束</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE emp5(</span><br><span class="line">id INT NOT NULL AUTO_INCREMENT,</span><br><span class="line">NAME VARCHAR(20),</span><br><span class="line">pwd VARCHAR(15),</span><br><span class="line">CONSTRAINT emp5_id_pk PRIMARY KEY(id)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<p>（2）建表后增加主键约束</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ALTER TABLE 表名称 ADD PRIMARY KEY(字段列表); #字段列表可以是一个字段，也可以是多个字段，如果是多个字段的话，是复合主键</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ALTER TABLE student ADD PRIMARY KEY (sid);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ALTER TABLE emp5 ADD PRIMARY KEY(NAME,pwd);</span><br></pre></td></tr></table></figure>
<h3 id="4-5-关于复合主键"><a href="#4-5-关于复合主键" class="headerlink" title="4.5 关于复合主键"></a>4.5 关于复合主键</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">create table 表名称(</span><br><span class="line">	字段名  数据类型,</span><br><span class="line">    字段名  数据类型,  </span><br><span class="line">    字段名  数据类型,</span><br><span class="line">    primary key(字段名1,字段名2)  #表示字段1和字段2的组合是唯一的，也可以有更多个字段</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">#学生表</span><br><span class="line">create table student(</span><br><span class="line">	sid int primary key,  #学号</span><br><span class="line">    sname varchar(20)     #学生姓名</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">#课程表</span><br><span class="line">create table course(</span><br><span class="line">	cid int primary key,  #课程编号</span><br><span class="line">    cname varchar(20)     #课程名称</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">#选课表</span><br><span class="line">create table student_course(</span><br><span class="line">	sid int,</span><br><span class="line">    cid int,</span><br><span class="line">    score int,</span><br><span class="line">    primary key(sid,cid)  #复合主键</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">insert into student values(1,&#x27;张三&#x27;),(2,&#x27;李四&#x27;);</span><br><span class="line">insert into course values(1001,&#x27;Java&#x27;),(1002,&#x27;MySQL&#x27;);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; select * from student;</span><br><span class="line">+-----+-------+</span><br><span class="line">| sid | sname |</span><br><span class="line">+-----+-------+</span><br><span class="line">|   1 | 张三  |</span><br><span class="line">|   2 | 李四  |</span><br><span class="line">+-----+-------+</span><br><span class="line">2 rows in set (0.00 sec)</span><br><span class="line"></span><br><span class="line">mysql&gt; select * from course;</span><br><span class="line">+------+-------+</span><br><span class="line">| cid  | cname |</span><br><span class="line">+------+-------+</span><br><span class="line">| 1001 | Java  |</span><br><span class="line">| 1002 | MySQL |</span><br><span class="line">+------+-------+</span><br><span class="line">2 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">insert into student_course values(1, 1001, 89),(1,1002,90),(2,1001,88),(2,1002,56);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; select * from student_course;</span><br><span class="line">+-----+------+-------+</span><br><span class="line">| sid | cid  | score |</span><br><span class="line">+-----+------+-------+</span><br><span class="line">|   1 | 1001 |    89 |</span><br><span class="line">|   1 | 1002 |    90 |</span><br><span class="line">|   2 | 1001 |    88 |</span><br><span class="line">|   2 | 1002 |    56 |</span><br><span class="line">+-----+------+-------+</span><br><span class="line">4 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">insert into student_course values(1, 1001, 100);</span><br><span class="line">ERROR 1062 (23000): Duplicate entry &#x27;1-1001&#x27; for key &#x27;PRIMARY&#x27;</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; desc student_course;</span><br><span class="line">+-------+---------+------+-----+---------+-------+</span><br><span class="line">| Field | Type    | Null | Key | Default | Extra |</span><br><span class="line">+-------+---------+------+-----+---------+-------+</span><br><span class="line">| sid   | int(11) | NO   | PRI | NULL    |       |</span><br><span class="line">| cid   | int(11) | NO   | PRI | NULL    |       |</span><br><span class="line">| score | int(11) | YES  |     | NULL    |       |</span><br><span class="line">+-------+---------+------+-----+---------+-------+</span><br><span class="line">3 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<ul>
<li>再举例</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE emp6(</span><br><span class="line">id INT NOT NULL,</span><br><span class="line">NAME VARCHAR(20),</span><br><span class="line">pwd VARCHAR(15),</span><br><span class="line">CONSTRAINT emp7_pk PRIMARY KEY(NAME,pwd)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<h3 id="4-6-删除主键约束"><a href="#4-6-删除主键约束" class="headerlink" title="4.6 删除主键约束"></a>4.6 删除主键约束</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alter table 表名称 drop primary key;</span><br></pre></td></tr></table></figure>
<p>举例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ALTER TABLE student DROP PRIMARY KEY;</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ALTER TABLE emp5 DROP PRIMARY KEY;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>说明：删除主键约束，不需要指定主键名，因为一个表只有一个主键，删除主键约束后，非空还存在。</p>
</blockquote>
<h2 id="5-自增列：AUTO-INCREMENT"><a href="#5-自增列：AUTO-INCREMENT" class="headerlink" title="5. 自增列：AUTO_INCREMENT"></a>5. 自增列：AUTO_INCREMENT</h2><h3 id="5-1-作用"><a href="#5-1-作用" class="headerlink" title="5.1 作用"></a>5.1 作用</h3><p>某个字段的值自增</p>
<h3 id="5-2-关键字"><a href="#5-2-关键字" class="headerlink" title="5.2 关键字"></a>5.2 关键字</h3><p>auto_increment</p>
<h3 id="5-3-特点和要求"><a href="#5-3-特点和要求" class="headerlink" title="5.3 特点和要求"></a>5.3 特点和要求</h3><p>（1）一个表最多只能有一个自增长列</p>
<p>（2）当需要产生唯一标识符或顺序值时，可设置自增长</p>
<p>（3）自增长列约束的列必须是键列（主键列，唯一键列）</p>
<p>（4）自增约束的列的数据类型必须是整数类型</p>
<p>（5）如果自增列指定了 0 和 null，会在当前最大值的基础上自增；如果自增列手动指定了具体值，直接赋值为具体值。</p>
<p>错误演示：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">create table employee(</span><br><span class="line">	eid int auto_increment,</span><br><span class="line">    ename varchar(20)</span><br><span class="line">);</span><br><span class="line"># ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key   </span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">create table employee(</span><br><span class="line">	eid int primary key,</span><br><span class="line">    ename varchar(20) unique key auto_increment</span><br><span class="line">);</span><br><span class="line"># ERROR 1063 (42000): Incorrect column specifier for column &#x27;ename&#x27;  因为ename不是整数类型</span><br></pre></td></tr></table></figure>
<h3 id="5-4-如何指定自增约束"><a href="#5-4-如何指定自增约束" class="headerlink" title="5.4 如何指定自增约束"></a>5.4 如何指定自增约束</h3><p><strong>（1）建表时</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">create table 表名称(</span><br><span class="line">	字段名  数据类型  primary key auto_increment,</span><br><span class="line">    字段名  数据类型  unique key not null,  </span><br><span class="line">    字段名  数据类型  unique key,</span><br><span class="line">    字段名  数据类型  not null default 默认值, </span><br><span class="line">);</span><br><span class="line">create table 表名称(</span><br><span class="line">	字段名  数据类型 default 默认值 ,</span><br><span class="line">    字段名  数据类型 unique key auto_increment,  </span><br><span class="line">    字段名  数据类型 not null default 默认值,,</span><br><span class="line">    primary key(字段名)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">create table employee(</span><br><span class="line">	eid int primary key auto_increment,</span><br><span class="line">    ename varchar(20)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; desc employee;</span><br><span class="line">+-------+-------------+------+-----+---------+----------------+</span><br><span class="line">| Field | Type        | Null | Key | Default | Extra          |</span><br><span class="line">+-------+-------------+------+-----+---------+----------------+</span><br><span class="line">| eid   | int(11)     | NO   | PRI | NULL    | auto_increment |</span><br><span class="line">| ename | varchar(20) | YES  |     | NULL    |                |</span><br><span class="line">+-------+-------------+------+-----+---------+----------------+</span><br><span class="line">2 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<p><strong>（2）建表后</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alter table 表名称 modify 字段名 数据类型 auto_increment;</span><br></pre></td></tr></table></figure>
<p>例如：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">create table employee(</span><br><span class="line">	eid int primary key ,</span><br><span class="line">    ename varchar(20)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alter table employee modify eid int auto_increment;</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; desc employee;</span><br><span class="line">+-------+-------------+------+-----+---------+----------------+</span><br><span class="line">| Field | Type        | Null | Key | Default | Extra          |</span><br><span class="line">+-------+-------------+------+-----+---------+----------------+</span><br><span class="line">| eid   | int(11)     | NO   | PRI | NULL    | auto_increment |</span><br><span class="line">| ename | varchar(20) | YES  |     | NULL    |                |</span><br><span class="line">+-------+-------------+------+-----+---------+----------------+</span><br><span class="line">2 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<h3 id="5-5-如何删除自增约束"><a href="#5-5-如何删除自增约束" class="headerlink" title="5.5 如何删除自增约束"></a>5.5 如何删除自增约束</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">#alter table 表名称 modify 字段名 数据类型 auto_increment;#给这个字段增加自增约束</span><br><span class="line"></span><br><span class="line">alter table 表名称 modify 字段名 数据类型; #去掉auto_increment相当于删除</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alter table employee modify eid int;</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; desc employee;</span><br><span class="line">+-------+-------------+------+-----+---------+-------+</span><br><span class="line">| Field | Type        | Null | Key | Default | Extra |</span><br><span class="line">+-------+-------------+------+-----+---------+-------+</span><br><span class="line">| eid   | int(11)     | NO   | PRI | NULL    |       |</span><br><span class="line">| ename | varchar(20) | YES  |     | NULL    |       |</span><br><span class="line">+-------+-------------+------+-----+---------+-------+</span><br><span class="line">2 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<h3 id="5-6-MySQL-8-0新特性—自增变量的持久化"><a href="#5-6-MySQL-8-0新特性—自增变量的持久化" class="headerlink" title="5.6 MySQL 8.0新特性—自增变量的持久化"></a>5.6 MySQL 8.0新特性—自增变量的持久化</h3><p>在MySQL 8.0之前，自增主键AUTO_INCREMENT的值如果大于max(primary key)+1，在MySQL重启后，会重置AUTO_INCREMENT=max(primary key)+1，这种现象在某些情况下会导致业务主键冲突或者其他难以发现的问题。<br>下面通过案例来对比不同的版本中自增变量是否持久化。<br>在MySQL 5.7版本中，测试步骤如下：<br>创建的数据表中包含自增主键的id字段，语句如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE test1(</span><br><span class="line">id INT PRIMARY KEY AUTO_INCREMENT</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<p>插入4个空值，执行如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">INSERT INTO test1</span><br><span class="line">VALUES(0),(0),(0),(0);</span><br></pre></td></tr></table></figure>
<p>查询数据表test1中的数据，结果如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; SELECT * FROM test1;</span><br><span class="line">+----+</span><br><span class="line">| id |</span><br><span class="line">+----+</span><br><span class="line">|  1 |</span><br><span class="line">|  2 |</span><br><span class="line">|  3 |</span><br><span class="line">|  4 |</span><br><span class="line">+----+</span><br><span class="line">4 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<p>删除id为4的记录，语句如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DELETE FROM test1 WHERE id = 4;</span><br></pre></td></tr></table></figure>
<p>再次插入一个空值，语句如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">INSERT INTO test1 VALUES(0);</span><br></pre></td></tr></table></figure>
<p>查询此时数据表test1中的数据，结果如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; SELECT * FROM test1;</span><br><span class="line">+----+</span><br><span class="line">| id |</span><br><span class="line">+----+</span><br><span class="line">|  1 |</span><br><span class="line">|  2 |</span><br><span class="line">|  3 |</span><br><span class="line">|  5 |</span><br><span class="line">+----+</span><br><span class="line">4 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<p>从结果可以看出，虽然删除了id为4的记录，但是再次插入空值时，并没有重用被删除的4，而是分配了5。<br>删除id为5的记录，结果如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DELETE FROM test1 where id=5;</span><br></pre></td></tr></table></figure>
<p><strong>重启数据库</strong>，重新插入一个空值。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">INSERT INTO test1 values(0);</span><br></pre></td></tr></table></figure>
<p>再次查询数据表test1中的数据，结果如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; SELECT * FROM test1;</span><br><span class="line">+----+</span><br><span class="line">| id |</span><br><span class="line">+----+</span><br><span class="line">|  1 |</span><br><span class="line">|  2 |</span><br><span class="line">|  3 |</span><br><span class="line">|  4 |</span><br><span class="line">+----+</span><br><span class="line">4 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<p>从结果可以看出，新插入的0值分配的是4，按照重启前的操作逻辑，此处应该分配6。出现上述结果的主要原因是自增主键没有持久化。<br>在MySQL 5.7系统中，对于自增主键的分配规则，是由InnoDB数据字典内部一个<code>计数器</code>来决定的，而该计数器只在<code>内存中维护</code>，并不会持久化到磁盘中。当数据库重启时，该计数器会被初始化。</p>
<p>在MySQL 8.0版本中，上述测试步骤最后一步的结果如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; SELECT * FROM test1;</span><br><span class="line">+----+</span><br><span class="line">| id |</span><br><span class="line">+----+</span><br><span class="line">|  1 |</span><br><span class="line">|  2 |</span><br><span class="line">|  3 |</span><br><span class="line">|  6 |</span><br><span class="line">+----+</span><br><span class="line">4 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<p>从结果可以看出，自增变量已经持久化了。</p>
<p>MySQL 8.0将自增主键的计数器持久化到<code>重做日志</code>中。每次计数器发生改变，都会将其写入重做日志中。如果数据库重启，InnoDB会根据重做日志中的信息来初始化计数器的内存值。</p>
<h2 id="6-FOREIGN-KEY-约束"><a href="#6-FOREIGN-KEY-约束" class="headerlink" title="6. FOREIGN KEY 约束"></a>6. FOREIGN KEY 约束</h2><h3 id="6-1-作用"><a href="#6-1-作用" class="headerlink" title="6.1 作用"></a>6.1 作用</h3><p>限定某个表的某个字段的引用完整性。</p>
<p>比如：员工表的员工所在部门的选择，必须在部门表能找到对应的部分。</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1555428214706.webp" alt="1555428214706"></p>
<h3 id="6-2-关键字"><a href="#6-2-关键字" class="headerlink" title="6.2 关键字"></a>6.2 关键字</h3><p>FOREIGN KEY</p>
<h3 id="6-3-主表和从表-父表和子表"><a href="#6-3-主表和从表-父表和子表" class="headerlink" title="6.3 主表和从表/父表和子表"></a>6.3 主表和从表/父表和子表</h3><p>主表（父表）：被引用的表，被参考的表</p>
<p>从表（子表）：引用别人的表，参考别人的表</p>
<p>例如：员工表的员工所在部门这个字段的值要参考部门表：部门表是主表，员工表是从表。</p>
<p>例如：学生表、课程表、选课表：选课表的学生和课程要分别参考学生表和课程表，学生表和课程表是主表，选课表是从表。</p>
<h3 id="6-4-特点"><a href="#6-4-特点" class="headerlink" title="6.4 特点"></a>6.4 特点</h3><p>（1）从表的外键列，必须引用/参考主表的主键或唯一约束的列</p>
<p>​          为什么？因为被依赖/被参考的值必须是唯一的</p>
<p>（2）在创建外键约束时，如果不给外键约束命名，<strong>默认名不是列名，而是自动产生一个外键名</strong>（例如 student_ibfk_1;），也可以指定外键约束名。</p>
<p>（3）创建(CREATE)表时就指定外键约束的话，先创建主表，再创建从表</p>
<p>（4）删表时，先删从表（或先删除外键约束），再删除主表</p>
<p>（5）当主表的记录被从表参照时，主表的记录将不允许删除，如果要删除数据，需要先删除从表中依赖该记录的数据，然后才可以删除主表的数据</p>
<p>（6）在“从表”中指定外键约束，并且一个表可以建立多个外键约束</p>
<p>（7）从表的外键列与主表被参照的列名字可以不相同，但是数据类型必须一样，逻辑意义一致。如果类型不一样，创建子表时，就会出现错误“ERROR 1005 (HY000): Can’t create table’database.tablename’(errno: 150)”。</p>
<p>​          例如：都是表示部门编号，都是int类型。</p>
<p>（8）<strong>当创建外键约束时，系统默认会在所在的列上建立对应的普通索引</strong>。但是索引名是外键的约束名。（根据外键查询效率很高）</p>
<p>（9）删除外键约束后，必须<code>手动</code>删除对应的索引</p>
<h3 id="6-5-添加外键约束"><a href="#6-5-添加外键约束" class="headerlink" title="6.5 添加外键约束"></a>6.5 添加外键约束</h3><p>（1）建表时</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">create table 主表名称(</span><br><span class="line">	字段1  数据类型  primary key,</span><br><span class="line">    字段2  数据类型</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">create table 从表名称(</span><br><span class="line">	字段1  数据类型  primary key,</span><br><span class="line">    字段2  数据类型,</span><br><span class="line">    [CONSTRAINT &lt;外键约束名称&gt;] FOREIGN KEY（从表的某个字段) references 主表名(被参考字段)</span><br><span class="line">);</span><br><span class="line">#(从表的某个字段)的数据类型必须与主表名(被参考字段)的数据类型一致，逻辑意义也一样</span><br><span class="line">#(从表的某个字段)的字段名可以与主表名(被参考字段)的字段名一样，也可以不一样</span><br><span class="line"></span><br><span class="line">-- FOREIGN KEY: 在表级指定子表中的列</span><br><span class="line">-- REFERENCES: 标示在父表中的列</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">create table dept( #主表</span><br><span class="line">	did int primary key,		#部门编号</span><br><span class="line">    dname varchar(50)			#部门名称</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">create table emp(#从表</span><br><span class="line">	eid int primary key,  #员工编号</span><br><span class="line">    ename varchar(5),     #员工姓名</span><br><span class="line">    deptid int,				#员工所在的部门</span><br><span class="line">    foreign key (deptid) references dept(did)   #在从表中指定外键约束</span><br><span class="line">    #emp表的deptid和和dept表的did的数据类型一致，意义都是表示部门的编号</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">说明：</span><br><span class="line">（1）主表dept必须先创建成功，然后才能创建emp表，指定外键成功。</span><br><span class="line">（2）删除表时，先删除从表emp，再删除主表dept</span><br></pre></td></tr></table></figure>
<p>（2）建表后</p>
<p>一般情况下，表与表的关联都是提前设计好了的，因此，会在创建表的时候就把外键约束定义好。不过，如果需要修改表的设计（比如添加新的字段，增加新的关联关系），但没有预先定义外键约束，那么，就要用修改表的方式来补充定义。</p>
<p>格式：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ALTER TABLE 从表名 ADD [CONSTRAINT 约束名] FOREIGN KEY (从表的字段) REFERENCES 主表名(被引用字段) [on update xx][on delete xx];</span><br></pre></td></tr></table></figure>
<p>举例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ALTER TABLE emp1</span><br><span class="line">ADD [CONSTRAINT emp_dept_id_fk] FOREIGN KEY(dept_id) REFERENCES dept(dept_id);</span><br></pre></td></tr></table></figure>
<p>举例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">create table dept(</span><br><span class="line">	did int primary key,		#部门编号</span><br><span class="line">    dname varchar(50)			#部门名称</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">create table emp(</span><br><span class="line">	eid int primary key,  #员工编号</span><br><span class="line">    ename varchar(5),     #员工姓名</span><br><span class="line">    deptid int				#员工所在的部门</span><br><span class="line">);</span><br><span class="line">#这两个表创建时，没有指定外键的话，那么创建顺序是随意</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alter table emp add foreign key (deptid) references dept(did);</span><br></pre></td></tr></table></figure>
<h3 id="6-6-演示问题"><a href="#6-6-演示问题" class="headerlink" title="6.6 演示问题"></a>6.6 演示问题</h3><p>（1）失败：不是键列</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">create table dept(</span><br><span class="line">	did int ,		#部门编号</span><br><span class="line">    dname varchar(50)			#部门名称</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">create table emp(</span><br><span class="line">	eid int primary key,  #员工编号</span><br><span class="line">    ename varchar(5),     #员工姓名</span><br><span class="line">    deptid int,				#员工所在的部门</span><br><span class="line">    foreign key (deptid) references dept(did)</span><br><span class="line">);</span><br><span class="line">#ERROR 1215 (HY000): Cannot add foreign key constraint  原因是dept的did不是键列</span><br></pre></td></tr></table></figure>
<p>（2）失败：数据类型不一致</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">create table dept(</span><br><span class="line">	did int primary key,		#部门编号</span><br><span class="line">    dname varchar(50)			#部门名称</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">create table emp(</span><br><span class="line">	eid int primary key,  #员工编号</span><br><span class="line">    ename varchar(5),     #员工姓名</span><br><span class="line">    deptid char,				#员工所在的部门</span><br><span class="line">    foreign key (deptid) references dept(did)</span><br><span class="line">);</span><br><span class="line">#ERROR 1215 (HY000): Cannot add foreign key constraint  原因是从表的deptid字段和主表的did字段的数据类型不一致，并且要它俩的逻辑意义一致</span><br></pre></td></tr></table></figure>
<p>（3）成功，两个表字段名一样</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">create table dept(</span><br><span class="line">	did int primary key,		#部门编号</span><br><span class="line">    dname varchar(50)			#部门名称</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">create table emp(</span><br><span class="line">	eid int primary key,  #员工编号</span><br><span class="line">    ename varchar(5),     #员工姓名</span><br><span class="line">    did int,				#员工所在的部门</span><br><span class="line">    foreign key (did) references dept(did)  </span><br><span class="line">    #emp表的deptid和和dept表的did的数据类型一致，意义都是表示部门的编号</span><br><span class="line">    #是否重名没问题，因为两个did在不同的表中</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<p>（4）添加、删除、修改问题</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">create table dept(</span><br><span class="line">	did int primary key,		#部门编号</span><br><span class="line">    dname varchar(50)			#部门名称</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">create table emp(</span><br><span class="line">	eid int primary key,  #员工编号</span><br><span class="line">    ename varchar(5),     #员工姓名</span><br><span class="line">    deptid int,				#员工所在的部门</span><br><span class="line">    foreign key (deptid) references dept(did)  </span><br><span class="line">    #emp表的deptid和和dept表的did的数据类型一致，意义都是表示部门的编号</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">insert into dept values(1001,&#x27;教学部&#x27;);</span><br><span class="line">insert into dept values(1003, &#x27;财务部&#x27;);</span><br><span class="line"></span><br><span class="line">insert into emp values(1,&#x27;张三&#x27;,1001); #添加从表记录成功，在添加这条记录时，要求部门表有1001部门</span><br><span class="line"></span><br><span class="line">insert into emp values(2,&#x27;李四&#x27;,1005);#添加从表记录失败</span><br><span class="line">ERROR 1452 (23000): Cannot add（添加） or update（修改） a child row: a foreign key constraint fails (`atguigudb`.`emp`, CONSTRAINT `emp_ibfk_1` FOREIGN KEY (`deptid`) REFERENCES `dept` (`did`)) 从表emp添加记录失败，因为主表dept没有1005部门</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; select * from dept;</span><br><span class="line">+------+--------+</span><br><span class="line">| did  | dname  |</span><br><span class="line">+------+--------+</span><br><span class="line">| 1001 | 教学部  |</span><br><span class="line">| 1003 | 财务部  |</span><br><span class="line">+------+--------+</span><br><span class="line">2 rows in set (0.00 sec)</span><br><span class="line"></span><br><span class="line">mysql&gt; select * from emp;</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">| eid | ename | deptid |</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">|   1 | 张三   |   1001 |</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">1 row in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">update emp set deptid = 1002 where eid = 1;#修改从表失败 </span><br><span class="line">ERROR 1452 (23000): Cannot add（添加） or update（修改） a child row（子表的记录）: a foreign key constraint fails（外键约束失败） (`atguigudb`.`emp`, CONSTRAINT `emp_ibfk_1` FOREIGN KEY (`deptid`) REFERENCES `dept` (`did`))  #部门表did字段现在没有1002的值，所以员工表中不能修改员工所在部门deptid为1002</span><br><span class="line"></span><br><span class="line">update dept set did = 1002 where did = 1001;#修改主表失败</span><br><span class="line">ERROR 1451 (23000): Cannot delete（删除） or update（修改） a parent row（父表的记录）: a foreign key constraint fails (`atguigudb`.`emp`, CONSTRAINT `emp_ibfk_1` FOREIGN KEY (`deptid`) REFERENCES `dept` (`did`)) #部门表did的1001字段已经被emp引用了，所以部门表的1001字段就不能修改了。</span><br><span class="line"></span><br><span class="line">update dept set did = 1002 where did = 1003;#修改主表成功  因为部门表的1003部门没有被emp表引用，所以可以修改</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">delete from dept where did=1001; #删除主表失败</span><br><span class="line">ERROR 1451 (23000): Cannot delete（删除） or update（修改） a parent row（父表记录）: a foreign key constraint fails (`atguigudb`.`emp`, CONSTRAINT `emp_ibfk_1` FOREIGN KEY (`deptid`) REFERENCES `dept` (`did`))  #因为部门表did的1001字段已经被emp引用了，所以部门表的1001字段对应的记录就不能被删除</span><br></pre></td></tr></table></figure>
<p>总结：约束关系是针对双方的</p>
<ul>
<li><p>添加了外键约束后，主表的修改和删除数据受约束</p>
</li>
<li><p>添加了外键约束后，从表的添加和修改数据受约束</p>
</li>
<li>在从表上建立外键，要求主表必须存在</li>
<li>删除主表时，要求从表从表先删除，或将从表中外键引用该主表的关系先删除</li>
</ul>
<h3 id="6-7-约束等级"><a href="#6-7-约束等级" class="headerlink" title="6.7 约束等级"></a>6.7 约束等级</h3><ul>
<li><p><code>Cascade方式</code>：在父表上update/delete记录时，同步update/delete掉子表的匹配记录 </p>
</li>
<li><p><code>Set null方式</code>：在父表上update/delete记录时，将子表上匹配记录的列设为null，但是要注意子表的外键列不能为not null  </p>
</li>
<li><p><code>No action方式</code>：如果子表中有匹配的记录，则不允许对父表对应候选键进行update/delete操作  </p>
</li>
<li><p><code>Restrict方式</code>：同no action， 都是立即检查外键约束</p>
</li>
<li><p><code>Set default方式</code>（在可视化工具SQLyog中可能显示空白）：父表有变更时，子表将外键列设置成一个默认的值，但Innodb不能识别</p>
</li>
</ul>
<p>如果没有指定等级，就相当于Restrict方式。</p>
<p>对于外键约束，最好是采用: <code>ON UPDATE CASCADE ON DELETE RESTRICT</code> 的方式。</p>
<p>（1）演示1：on update cascade on delete set null</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">create table dept(</span><br><span class="line">	did int primary key,		#部门编号</span><br><span class="line">    dname varchar(50)			#部门名称</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">create table emp(</span><br><span class="line">	eid int primary key,  #员工编号</span><br><span class="line">    ename varchar(5),     #员工姓名</span><br><span class="line">    deptid int,				#员工所在的部门</span><br><span class="line">    foreign key (deptid) references dept(did)  on update cascade on delete set null</span><br><span class="line">    #把修改操作设置为级联修改等级，把删除操作设置为set null等级</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">insert into dept values(1001,&#x27;教学部&#x27;);</span><br><span class="line">insert into dept values(1002, &#x27;财务部&#x27;);</span><br><span class="line">insert into dept values(1003, &#x27;咨询部&#x27;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">insert into emp values(1,&#x27;张三&#x27;,1001); #在添加这条记录时，要求部门表有1001部门</span><br><span class="line">insert into emp values(2,&#x27;李四&#x27;,1001);</span><br><span class="line">insert into emp values(3,&#x27;王五&#x27;,1002);</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; select * from dept;</span><br><span class="line"></span><br><span class="line">mysql&gt; select * from emp;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">#修改主表成功，从表也跟着修改，修改了主表被引用的字段1002为1004，从表的引用字段就跟着修改为1004了</span><br><span class="line">mysql&gt; update dept set did = 1004 where did = 1002;</span><br><span class="line">Query OK, 1 row affected (0.00 sec)</span><br><span class="line">Rows matched: 1  Changed: 1  Warnings: 0</span><br><span class="line"></span><br><span class="line">mysql&gt; select * from dept;</span><br><span class="line">+------+--------+</span><br><span class="line">| did  | dname  |</span><br><span class="line">+------+--------+</span><br><span class="line">| 1001 | 教学部 |</span><br><span class="line">| 1003 | 咨询部 |</span><br><span class="line">| 1004 | 财务部 | #原来是1002，修改为1004</span><br><span class="line">+------+--------+</span><br><span class="line">3 rows in set (0.00 sec)</span><br><span class="line"></span><br><span class="line">mysql&gt; select * from emp;</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">| eid | ename | deptid |</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">|   1 | 张三  |   1001 |</span><br><span class="line">|   2 | 李四  |   1001 |</span><br><span class="line">|   3 | 王五  |   1004 | #原来是1002，跟着修改为1004</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">3 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">#删除主表的记录成功，从表对应的字段的值被修改为null</span><br><span class="line">mysql&gt; delete from dept where did = 1001;</span><br><span class="line">Query OK, 1 row affected (0.01 sec)</span><br><span class="line"></span><br><span class="line">mysql&gt; select * from dept;</span><br><span class="line">+------+--------+</span><br><span class="line">| did  | dname  | #记录1001部门被删除了</span><br><span class="line">+------+--------+</span><br><span class="line">| 1003 | 咨询部  |</span><br><span class="line">| 1004 | 财务部  |</span><br><span class="line">+------+--------+</span><br><span class="line">2 rows in set (0.00 sec)</span><br><span class="line"></span><br><span class="line">mysql&gt; select * from emp;</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">| eid | ename | deptid |</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">|   1 | 张三  |   NULL | #原来引用1001部门的员工，deptid字段变为null</span><br><span class="line">|   2 | 李四  |   NULL |</span><br><span class="line">|   3 | 王五  |   1004 |</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">3 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<p>（2）演示2：on update set null on delete cascade</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">create table dept(</span><br><span class="line">	did int primary key,		#部门编号</span><br><span class="line">    dname varchar(50)			#部门名称</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">create table emp(</span><br><span class="line">	eid int primary key,  #员工编号</span><br><span class="line">    ename varchar(5),     #员工姓名</span><br><span class="line">    deptid int,				#员工所在的部门</span><br><span class="line">    foreign key (deptid) references dept(did)  on update set null on delete cascade</span><br><span class="line">    #把修改操作设置为set null等级，把删除操作设置为级联删除等级</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">insert into dept values(1001,&#x27;教学部&#x27;);</span><br><span class="line">insert into dept values(1002, &#x27;财务部&#x27;);</span><br><span class="line">insert into dept values(1003, &#x27;咨询部&#x27;);</span><br><span class="line"></span><br><span class="line">insert into emp values(1,&#x27;张三&#x27;,1001); #在添加这条记录时，要求部门表有1001部门</span><br><span class="line">insert into emp values(2,&#x27;李四&#x27;,1001);</span><br><span class="line">insert into emp values(3,&#x27;王五&#x27;,1002);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; select * from dept;</span><br><span class="line">+------+--------+</span><br><span class="line">| did  | dname  |</span><br><span class="line">+------+--------+</span><br><span class="line">| 1001 | 教学部 |</span><br><span class="line">| 1002 | 财务部 |</span><br><span class="line">| 1003 | 咨询部 |</span><br><span class="line">+------+--------+</span><br><span class="line">3 rows in set (0.00 sec)</span><br><span class="line"></span><br><span class="line">mysql&gt; select * from emp;</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">| eid | ename | deptid |</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">|   1 | 张三  |   1001 |</span><br><span class="line">|   2 | 李四  |   1001 |</span><br><span class="line">|   3 | 王五  |   1002 |</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">3 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">#修改主表，从表对应的字段设置为null</span><br><span class="line">mysql&gt; update dept set did = 1004 where did = 1002;</span><br><span class="line">Query OK, 1 row affected (0.00 sec)</span><br><span class="line">Rows matched: 1  Changed: 1  Warnings: 0</span><br><span class="line"></span><br><span class="line">mysql&gt; select * from dept;</span><br><span class="line">+------+--------+</span><br><span class="line">| did  | dname  |</span><br><span class="line">+------+--------+</span><br><span class="line">| 1001 | 教学部 |</span><br><span class="line">| 1003 | 咨询部 |</span><br><span class="line">| 1004 | 财务部 | #原来did是1002</span><br><span class="line">+------+--------+</span><br><span class="line">3 rows in set (0.00 sec)</span><br><span class="line"></span><br><span class="line">mysql&gt; select * from emp;</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">| eid | ename | deptid |</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">|   1 | 张三  |   1001 |</span><br><span class="line">|   2 | 李四  |   1001 |</span><br><span class="line">|   3 | 王五  |   NULL | #原来deptid是1002，因为部门表1002被修改了，1002没有对应的了，就设置为null</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">3 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">#删除主表的记录成功，主表的1001行被删除了，从表相应的记录也被删除了</span><br><span class="line">mysql&gt; delete from dept where did=1001;</span><br><span class="line">Query OK, 1 row affected (0.00 sec)</span><br><span class="line"></span><br><span class="line">mysql&gt; select * from dept;</span><br><span class="line">+------+--------+</span><br><span class="line">| did  | dname  | #部门表中1001部门被删除</span><br><span class="line">+------+--------+</span><br><span class="line">| 1003 | 咨询部 |</span><br><span class="line">| 1004 | 财务部 |</span><br><span class="line">+------+--------+</span><br><span class="line">2 rows in set (0.00 sec)</span><br><span class="line"></span><br><span class="line">mysql&gt; select * from emp;</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">| eid | ename | deptid |#原来1001部门的员工也被删除了</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">|   3 | 王五  |   NULL |</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">1 row in set (0.00 sec)</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>（3）演示：on update cascade on delete cascade</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">create table dept(</span><br><span class="line">	did int primary key,		#部门编号</span><br><span class="line">    dname varchar(50)			#部门名称</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">create table emp(</span><br><span class="line">	eid int primary key,  #员工编号</span><br><span class="line">    ename varchar(5),     #员工姓名</span><br><span class="line">    deptid int,				#员工所在的部门</span><br><span class="line">    foreign key (deptid) references dept(did)  on update cascade on delete cascade</span><br><span class="line">    #把修改操作设置为级联修改等级，把删除操作也设置为级联删除等级</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">insert into dept values(1001,&#x27;教学部&#x27;);</span><br><span class="line">insert into dept values(1002, &#x27;财务部&#x27;);</span><br><span class="line">insert into dept values(1003, &#x27;咨询部&#x27;);</span><br><span class="line"></span><br><span class="line">insert into emp values(1,&#x27;张三&#x27;,1001); #在添加这条记录时，要求部门表有1001部门</span><br><span class="line">insert into emp values(2,&#x27;李四&#x27;,1001);</span><br><span class="line">insert into emp values(3,&#x27;王五&#x27;,1002);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; select * from dept;</span><br><span class="line">+------+--------+</span><br><span class="line">| did  | dname  |</span><br><span class="line">+------+--------+</span><br><span class="line">| 1001 | 教学部 |</span><br><span class="line">| 1002 | 财务部 |</span><br><span class="line">| 1003 | 咨询部 |</span><br><span class="line">+------+--------+</span><br><span class="line">3 rows in set (0.00 sec)</span><br><span class="line"></span><br><span class="line">mysql&gt; select * from emp;</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">| eid | ename | deptid |</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">|   1 | 张三  |   1001 |</span><br><span class="line">|   2 | 李四  |   1001 |</span><br><span class="line">|   3 | 王五  |   1002 |</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">3 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">#修改主表，从表对应的字段自动修改</span><br><span class="line">mysql&gt; update dept set did = 1004 where did = 1002;</span><br><span class="line">Query OK, 1 row affected (0.00 sec)</span><br><span class="line">Rows matched: 1  Changed: 1  Warnings: 0</span><br><span class="line"></span><br><span class="line">mysql&gt; select * from dept;</span><br><span class="line">+------+--------+</span><br><span class="line">| did  | dname  |</span><br><span class="line">+------+--------+</span><br><span class="line">| 1001 | 教学部 |</span><br><span class="line">| 1003 | 咨询部 |</span><br><span class="line">| 1004 | 财务部 | #部门1002修改为1004</span><br><span class="line">+------+--------+</span><br><span class="line">3 rows in set (0.00 sec)</span><br><span class="line"></span><br><span class="line">mysql&gt; select * from emp;</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">| eid | ename | deptid |</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">|   1 | 张三  |   1001 |</span><br><span class="line">|   2 | 李四  |   1001 |</span><br><span class="line">|   3 | 王五  |   1004 | #级联修改</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">3 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">#删除主表的记录成功，主表的1001行被删除了，从表相应的记录也被删除了</span><br><span class="line">mysql&gt; delete from dept where did=1001;</span><br><span class="line">Query OK, 1 row affected (0.00 sec)</span><br><span class="line"></span><br><span class="line">mysql&gt; select * from dept;</span><br><span class="line">+------+--------+</span><br><span class="line">| did  | dname  | #1001部门被删除了</span><br><span class="line">+------+--------+</span><br><span class="line">| 1003 | 咨询部 |</span><br><span class="line">| 1004 | 财务部 | </span><br><span class="line">+------+--------+</span><br><span class="line">2 rows in set (0.00 sec)</span><br><span class="line"></span><br><span class="line">mysql&gt; select * from emp;</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">| eid | ename | deptid |  #1001部门的员工也被删除了</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">|   3 | 王五  |   1004 |</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">1 row in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<h3 id="6-8-删除外键约束"><a href="#6-8-删除外键约束" class="headerlink" title="6.8 删除外键约束"></a>6.8 删除外键约束</h3><p>流程如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">(1)第一步先查看约束名和删除外键约束</span><br><span class="line">SELECT * FROM information_schema.table_constraints WHERE table_name = &#x27;表名称&#x27;;#查看某个表的约束名</span><br><span class="line"></span><br><span class="line">ALTER TABLE 从表名 DROP FOREIGN KEY 外键约束名;</span><br><span class="line"></span><br><span class="line">（2）第二步查看索引名和删除索引。（注意，只能手动删除）</span><br><span class="line">SHOW INDEX FROM 表名称; #查看某个表的索引名</span><br><span class="line"></span><br><span class="line">ALTER TABLE 从表名 DROP INDEX 索引名;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>举例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; SELECT * FROM information_schema.table_constraints WHERE table_name = &#x27;emp&#x27;;</span><br><span class="line"></span><br><span class="line">mysql&gt; alter table emp drop foreign key emp_ibfk_1;</span><br><span class="line">Query OK, 0 rows affected (0.02 sec)</span><br><span class="line">Records: 0  Duplicates: 0  Warnings: 0</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; show index from emp;</span><br><span class="line"></span><br><span class="line">mysql&gt; alter table emp drop index deptid;</span><br><span class="line">Query OK, 0 rows affected (0.01 sec)</span><br><span class="line">Records: 0  Duplicates: 0  Warnings: 0</span><br><span class="line"></span><br><span class="line">mysql&gt;  show index from emp;</span><br></pre></td></tr></table></figure>
<h3 id="6-9-开发场景"><a href="#6-9-开发场景" class="headerlink" title="6.9 开发场景"></a>6.9 开发场景</h3><p><strong>问题1：如果两个表之间有关系（一对一、一对多），比如：员工表和部门表（一对多），它们之间是否一定要建外键约束？</strong></p>
<p>答：不是的</p>
<p><strong>问题2：建和不建外键约束有什么区别？</strong></p>
<p>答：建外键约束，你的操作（创建表、删除表、添加、修改、删除）会受到限制，从语法层面受到限制。例如：在员工表中不可能添加一个员工信息，它的部门的值在部门表中找不到。</p>
<p>不建外键约束，你的操作（创建表、删除表、添加、修改、删除）不受限制，要保证数据的<code>引用完整性</code>，只能依<code>靠程序员的自觉</code>，或者是<code>在Java程序中进行限定</code>。例如：在员工表中，可以添加一个员工的信息，它的部门指定为一个完全不存在的部门。</p>
<p><strong>问题3：那么建和不建外键约束和查询有没有关系？</strong></p>
<p>答：没有</p>
<blockquote>
<p>在 MySQL 里，外键约束是有成本的，需要消耗系统资源。对于大并发的 SQL 操作，有可能会不适合。比如大型网站的中央数据库，可能会<code>因为外键约束的系统开销而变得非常慢</code>。所以， MySQL 允许你不使用系统自带的外键约束，在<code>应用层面</code>完成检查数据一致性的逻辑。也就是说，即使你不用外键约束，也要想办法通过应用层面的附加逻辑，来实现外键约束的功能，确保数据的一致性。</p>
</blockquote>
<h3 id="6-10-阿里开发规范"><a href="#6-10-阿里开发规范" class="headerlink" title="6.10 阿里开发规范"></a>6.10 阿里开发规范</h3><p>【<code>强制</code>】不得使用外键与级联，一切外键概念必须在应用层解决。 </p>
<p>说明：（概念解释）学生表中的 student_id 是主键，那么成绩表中的 student_id 则为外键。如果更新学生表中的 student_id，同时触发成绩表中的 student_id 更新，即为级联更新。外键与级联更新适用于<code>单机低并发</code>，不适合<code>分布式</code>、<code>高并发集群</code>；级联更新是强阻塞，存在数据库<code>更新风暴</code>的风险；外键影响数据库的<code>插入速度</code>。</p>
<h2 id="7-CHECK-约束"><a href="#7-CHECK-约束" class="headerlink" title="7. CHECK 约束"></a>7. CHECK 约束</h2><h3 id="7-1-作用"><a href="#7-1-作用" class="headerlink" title="7.1 作用"></a>7.1 作用</h3><p>检查某个字段的值是否符号xx要求，一般指的是值的范围</p>
<h3 id="2、关键字"><a href="#2、关键字" class="headerlink" title="2、关键字"></a>2、关键字</h3><p>CHECK</p>
<h3 id="3、说明：MySQL-5-7-不支持"><a href="#3、说明：MySQL-5-7-不支持" class="headerlink" title="3、说明：MySQL 5.7 不支持"></a>3、说明：MySQL 5.7 不支持</h3><p>MySQL5.7 可以使用check约束，但check约束对数据验证没有任何作用。添加数据时，没有任何错误或警告</p>
<p>但是<strong>MySQL 8.0中可以使用check约束了</strong>。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">create table employee(</span><br><span class="line">	eid int primary key,</span><br><span class="line">    ename varchar(5),</span><br><span class="line">    gender char check (&#x27;男&#x27; or &#x27;女&#x27;)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">insert into employee values(1,&#x27;张三&#x27;,&#x27;妖&#x27;);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; select * from employee;</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">| eid | ename | gender |</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">|   1 | 张三   | 妖     |</span><br><span class="line">+-----+-------+--------+</span><br><span class="line">1 row in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<ul>
<li>再举例</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE temp(</span><br><span class="line">id INT AUTO_INCREMENT,</span><br><span class="line">NAME VARCHAR(20),</span><br><span class="line">age INT CHECK(age &gt; 20),</span><br><span class="line">PRIMARY KEY(id)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<ul>
<li>再举例</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">age tinyint check(age &gt;20) 或 sex char(2) check(sex in(‘男’,’女’))</span><br></pre></td></tr></table></figure>
<ul>
<li>再举例</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">CHECK(height&gt;=0 AND height&lt;3)</span><br></pre></td></tr></table></figure>
<h2 id="8-DEFAULT约束"><a href="#8-DEFAULT约束" class="headerlink" title="8. DEFAULT约束"></a>8. DEFAULT约束</h2><h3 id="8-1-作用"><a href="#8-1-作用" class="headerlink" title="8.1 作用"></a>8.1 作用</h3><p>给某个字段/某列指定默认值，一旦设置默认值，在插入数据时，如果此字段没有显式赋值，则赋值为默认值。</p>
<h3 id="8-2-关键字"><a href="#8-2-关键字" class="headerlink" title="8.2 关键字"></a>8.2 关键字</h3><p>DEFAULT</p>
<h3 id="8-3-如何给字段加默认值"><a href="#8-3-如何给字段加默认值" class="headerlink" title="8.3 如何给字段加默认值"></a>8.3 如何给字段加默认值</h3><p>（1）建表时</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">create table 表名称(</span><br><span class="line">	字段名  数据类型  primary key,</span><br><span class="line">    字段名  数据类型  unique key not null,  </span><br><span class="line">    字段名  数据类型  unique key,</span><br><span class="line">    字段名  数据类型  not null default 默认值, </span><br><span class="line">);</span><br><span class="line">create table 表名称(</span><br><span class="line">	字段名  数据类型 default 默认值 ,</span><br><span class="line">    字段名  数据类型 not null default 默认值,  </span><br><span class="line">    字段名  数据类型 not null default 默认值,</span><br><span class="line">    primary key(字段名),</span><br><span class="line">    unique key(字段名)</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">说明：默认值约束一般不在唯一键和主键列上加</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">create table employee(</span><br><span class="line">	eid int primary key,</span><br><span class="line">    ename varchar(20) not null,</span><br><span class="line">    gender char default &#x27;男&#x27;,</span><br><span class="line">    tel char(11) not null default &#x27;&#x27; #默认是空字符串</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; desc employee;</span><br><span class="line">+--------+-------------+------+-----+---------+-------+</span><br><span class="line">| Field  | Type        | Null | Key | Default | Extra |</span><br><span class="line">+--------+-------------+------+-----+---------+-------+</span><br><span class="line">| eid    | int(11)     | NO   | PRI | NULL    |       |</span><br><span class="line">| ename  | varchar(20) | NO   |     | NULL    |       |</span><br><span class="line">| gender | char(1)     | YES  |     | 男      |       |</span><br><span class="line">| tel    | char(11)    | NO   |     |         |       |</span><br><span class="line">+--------+-------------+------+-----+---------+-------+</span><br><span class="line">4 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">insert into employee values(1,&#x27;汪飞&#x27;,&#x27;男&#x27;,&#x27;13700102535&#x27;); #成功</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; select * from employee;</span><br><span class="line">+-----+-------+--------+-------------+</span><br><span class="line">| eid | ename | gender | tel         |</span><br><span class="line">+-----+-------+--------+-------------+</span><br><span class="line">|   1 | 汪飞  | 男     | 13700102535 |</span><br><span class="line">+-----+-------+--------+-------------+</span><br><span class="line">1 row in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">insert into employee(eid,ename) values(2,&#x27;天琪&#x27;); #成功</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; select * from employee;</span><br><span class="line">+-----+-------+--------+-------------+</span><br><span class="line">| eid | ename | gender | tel         |</span><br><span class="line">+-----+-------+--------+-------------+</span><br><span class="line">|   1 | 汪飞  | 男     | 13700102535 |</span><br><span class="line">|   2 | 天琪  | 男     |             |</span><br><span class="line">+-----+-------+--------+-------------+</span><br><span class="line">2 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">insert into employee(eid,ename) values(3,&#x27;二虎&#x27;);</span><br><span class="line">#ERROR 1062 (23000): Duplicate entry &#x27;&#x27; for key &#x27;tel&#x27;  </span><br><span class="line">#如果tel有唯一性约束的话会报错，如果tel没有唯一性约束，可以添加成功</span><br></pre></td></tr></table></figure>
<p>再举例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE myemp(</span><br><span class="line">id INT AUTO_INCREMENT PRIMARY KEY,</span><br><span class="line">NAME VARCHAR(15),</span><br><span class="line">salary DOUBLE(10,2) DEFAULT 2000</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<p>（2）建表后</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">alter table 表名称 modify 字段名 数据类型 default 默认值;</span><br><span class="line"></span><br><span class="line">#如果这个字段原来有非空约束，你还保留非空约束，那么在加默认值约束时，还得保留非空约束，否则非空约束就被删除了</span><br><span class="line">#同理，在给某个字段加非空约束也一样，如果这个字段原来有默认值约束，你想保留，也要在modify语句中保留默认值约束，否则就删除了</span><br><span class="line">alter table 表名称 modify 字段名 数据类型 default 默认值 not null;</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">create table employee(</span><br><span class="line">	eid int primary key,</span><br><span class="line">    ename varchar(20),</span><br><span class="line">    gender char,</span><br><span class="line">    tel char(11) not null</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; desc employee;</span><br><span class="line">+--------+-------------+------+-----+---------+-------+</span><br><span class="line">| Field  | Type        | Null | Key | Default | Extra |</span><br><span class="line">+--------+-------------+------+-----+---------+-------+</span><br><span class="line">| eid    | int(11)     | NO   | PRI | NULL    |       |</span><br><span class="line">| ename  | varchar(20) | YES  |     | NULL    |       |</span><br><span class="line">| gender | char(1)     | YES  |     | NULL    |       |</span><br><span class="line">| tel    | char(11)    | NO   |     | NULL    |       |</span><br><span class="line">+--------+-------------+------+-----+---------+-------+</span><br><span class="line">4 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">alter table employee modify gender char default &#x27;男&#x27;;  #给gender字段增加默认值约束</span><br><span class="line">alter table employee modify tel char(11) default &#x27;&#x27;; #给tel字段增加默认值约束</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; desc employee;</span><br><span class="line">+--------+-------------+------+-----+---------+-------+</span><br><span class="line">| Field  | Type        | Null | Key | Default | Extra |</span><br><span class="line">+--------+-------------+------+-----+---------+-------+</span><br><span class="line">| eid    | int(11)     | NO   | PRI | NULL    |       |</span><br><span class="line">| ename  | varchar(20) | YES  |     | NULL    |       |</span><br><span class="line">| gender | char(1)     | YES  |     | 男      |       |</span><br><span class="line">| tel    | char(11)    | YES  |     |         |       |</span><br><span class="line">+--------+-------------+------+-----+---------+-------+</span><br><span class="line">4 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alter table employee modify tel char(11) default &#x27;&#x27;  not null;#给tel字段增加默认值约束，并保留非空约束</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; desc employee;</span><br><span class="line">+--------+-------------+------+-----+---------+-------+</span><br><span class="line">| Field  | Type        | Null | Key | Default | Extra |</span><br><span class="line">+--------+-------------+------+-----+---------+-------+</span><br><span class="line">| eid    | int(11)     | NO   | PRI | NULL    |       |</span><br><span class="line">| ename  | varchar(20) | YES  |     | NULL    |       |</span><br><span class="line">| gender | char(1)     | YES  |     | 男      |       |</span><br><span class="line">| tel    | char(11)    | NO   |     |         |       |</span><br><span class="line">+--------+-------------+------+-----+---------+-------+</span><br><span class="line">4 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<h3 id="8-4-如何删除默认值约束"><a href="#8-4-如何删除默认值约束" class="headerlink" title="8.4 如何删除默认值约束"></a>8.4 如何删除默认值约束</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">alter table 表名称 modify 字段名 数据类型 ;#删除默认值约束，也不保留非空约束</span><br><span class="line"></span><br><span class="line">alter table 表名称 modify 字段名 数据类型  not null; #删除默认值约束，保留非空约束</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">alter table employee modify gender char; #删除gender字段默认值约束，如果有非空约束，也一并删除</span><br><span class="line">alter table employee modify tel char(11)  not null;#删除tel字段默认值约束，保留非空约束</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; desc employee;</span><br><span class="line">+--------+-------------+------+-----+---------+-------+</span><br><span class="line">| Field  | Type        | Null | Key | Default | Extra |</span><br><span class="line">+--------+-------------+------+-----+---------+-------+</span><br><span class="line">| eid    | int(11)     | NO   | PRI | NULL    |       |</span><br><span class="line">| ename  | varchar(20) | YES  |     | NULL    |       |</span><br><span class="line">| gender | char(1)     | YES  |     | NULL    |       |</span><br><span class="line">| tel    | char(11)    | NO   |     | NULL    |       |</span><br><span class="line">+--------+-------------+------+-----+---------+-------+</span><br><span class="line">4 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<h2 id="9-面试"><a href="#9-面试" class="headerlink" title="9. 面试"></a>9. 面试</h2><p><strong>面试1、为什么建表时，加 not null default ‘’ 或 default 0</strong></p>
<p>答：不想让表中出现null值。</p>
<p><strong>面试2、为什么不想要 null 的值</strong></p>
<p>答:（1）不好比较。null是一种特殊值，比较时只能用专门的is null 和 is not null来比较。碰到运算符，通常返回null。</p>
<p>​     （2）效率不高。影响提高索引效果。因此，我们往往在建表时 not null default ‘’ 或 default 0</p>
<p><strong>面试3、带AUTO_INCREMENT约束的字段值是从1开始的吗？</strong><br>在MySQL中，默认AUTO_INCREMENT的初始值是1，每新增一条记录，字段值自动加1。设置自增属性（AUTO_INCREMENT）的时候，还可以指定第一条插入记录的自增字段的值，这样新插入的记录的自增字段值从初始值开始递增，如在表中插入第一条记录，同时指定id值为5，则以后插入的记录的id值就会从6开始往上增加。添加主键约束时，往往需要设置字段自动增加属性。</p>
<p><strong>面试4、并不是每个表都可以任意选择存储引擎？</strong><br>外键约束（FOREIGN KEY）不能跨引擎使用。</p>
<p>MySQL支持多种存储引擎，每一个表都可以指定一个不同的存储引擎，需要注意的是：外键约束是用来保证数据的参照完整性的，如果表之间需要关联外键，却指定了不同的存储引擎，那么这些表之间是不能创建外键约束的。所以说，存储引擎的选择也不完全是随意的。</p>
</article><div class="post-copyright"><div class="post-copyright__title"><span class="post-copyright-info"><h>第十三-MySQL约束</h></span></div><div class="post-copyright__type"><span class="post-copyright-info"><a href="https://www.naste.top:1024/posts/986000951.html">https://www.naste.top:1024/posts/986000951.html</a></span></div><div class="post-copyright-m"><div class="post-copyright-m-info"><div class="post-copyright-a"><h>作者</h><div class="post-copyright-cc-info"><h>XiaoFei🥝</h></div></div><div class="post-copyright-c"><h>发布于</h><div class="post-copyright-cc-info"><h>2022-09-19</h></div></div><div class="post-copyright-u"><h>更新于</h><div class="post-copyright-cc-info"><h>2024-04-26</h></div></div><div class="post-copyright-c"><h>许可协议</h><div class="post-copyright-cc-info"><a class="icon" rel="noopener" target="_blank" title="Creative Commons" href="https://creativecommons.org/"><i class="fab fa-creative-commons"></i></a><a rel="noopener" target="_blank" title="CC BY-NC-SA 4.0" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a></div></div></div></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/MySQL/"><div class="tags-punctuation"><svg class="faa-tada icon" style="height:1.1em;width:1.1em;fill:currentColor;position:relative;top:2px;margin-right:3px" aria-hidden="true"><use xlink:href="#icon-sekuaibiaoqian"></use></svg></div>MySQL</a></div></div><link rel="stylesheet" href="/css/coin.css" media="defer" onload="this.media='all'"/><div class="post-reward"><button class="tip-button reward-button"><span class="tip-button__text">投喂作者</span><div class="coin-wrapper"><div class="coin"><div class="coin__middle"></div><div class="coin__back"></div><div class="coin__front"></div></div></div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://www.naste.top:9000/images/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://www.naste.top:9000/images/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://www.naste.top:9000/images/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://www.naste.top:9000/images/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></button></div><audio id="coinAudio" src="https://npm.elemecdn.com/akilar-candyassets@1.0.36/audio/aowu.m4a"></audio><script defer="defer" src="/js/coin.js"></script><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/922876948.html"><img class="prev-cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1675912183.webp" onerror="onerror=null;src='/assets/r2.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">第十四-MySQL视图</div></div></a></div><div class="next-post pull-right"><a href="/posts/2511742921.html"><img class="next-cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1675912190.webp" onerror="onerror=null;src='/assets/r2.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">第十二-MySQL数据类型精讲</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/2414116852.html" title="JDBC"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1515952743784.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">JDBC</div></div></a></div><div><a href="/posts/3169224211.html" title="MySQL基础"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1675912182.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">MySQL基础</div></div></a></div><div><a href="/posts/316116237.html" title="MySQL数据库备份"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1675912176.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">MySQL数据库备份</div></div></a></div><div><a href="/posts/994286255.html" title="Mysql的表无法修改、删除等操作，卡死、锁死情况的处理办法"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1678672925.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">Mysql的表无法修改、删除等操作，卡死、锁死情况的处理办法</div></div></a></div><div><a href="/posts/75c6e52f.html" title="MySQL基本使用"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1515952743786.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">MySQL基本使用</div></div></a></div><div><a href="/posts/2844609012.html" title="第零-MySQL写在前面"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1675912181.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">第零-MySQL写在前面</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><svg class="meta_icon" style="width:22px;height:22px;position:relative;top:5px"><use xlink:href="#icon-mulu1"></use></svg><span style="font-weight:bold">目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC13%E7%AB%A0-%E7%BA%A6%E6%9D%9F"><span class="toc-text">第13章_约束</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E7%BA%A6%E6%9D%9F-constraint-%E6%A6%82%E8%BF%B0"><span class="toc-text">1. 约束(constraint)概述</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-%E4%B8%BA%E4%BB%80%E4%B9%88%E9%9C%80%E8%A6%81%E7%BA%A6%E6%9D%9F"><span class="toc-text">1.1 为什么需要约束</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-%E4%BB%80%E4%B9%88%E6%98%AF%E7%BA%A6%E6%9D%9F"><span class="toc-text">1.2 什么是约束</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-3-%E7%BA%A6%E6%9D%9F%E7%9A%84%E5%88%86%E7%B1%BB"><span class="toc-text">1.3 约束的分类</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E9%9D%9E%E7%A9%BA%E7%BA%A6%E6%9D%9F"><span class="toc-text">2. 非空约束</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-%E4%BD%9C%E7%94%A8"><span class="toc-text">2.1 作用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-%E5%85%B3%E9%94%AE%E5%AD%97"><span class="toc-text">2.2 关键字</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-%E7%89%B9%E7%82%B9"><span class="toc-text">2.3 特点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-4-%E6%B7%BB%E5%8A%A0%E9%9D%9E%E7%A9%BA%E7%BA%A6%E6%9D%9F"><span class="toc-text">2.4 添加非空约束</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-5-%E5%88%A0%E9%99%A4%E9%9D%9E%E7%A9%BA%E7%BA%A6%E6%9D%9F"><span class="toc-text">2.5 删除非空约束</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-%E5%94%AF%E4%B8%80%E6%80%A7%E7%BA%A6%E6%9D%9F"><span class="toc-text">3. 唯一性约束</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-%E4%BD%9C%E7%94%A8"><span class="toc-text">3.1 作用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-%E5%85%B3%E9%94%AE%E5%AD%97"><span class="toc-text">3.2 关键字</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-3-%E7%89%B9%E7%82%B9"><span class="toc-text">3.3 特点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-4-%E6%B7%BB%E5%8A%A0%E5%94%AF%E4%B8%80%E7%BA%A6%E6%9D%9F"><span class="toc-text">3.4 添加唯一约束</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-5-%E5%85%B3%E4%BA%8E%E5%A4%8D%E5%90%88%E5%94%AF%E4%B8%80%E7%BA%A6%E6%9D%9F"><span class="toc-text">3.5 关于复合唯一约束</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-5-%E5%88%A0%E9%99%A4%E5%94%AF%E4%B8%80%E7%BA%A6%E6%9D%9F"><span class="toc-text">3.5 删除唯一约束</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-PRIMARY-KEY-%E7%BA%A6%E6%9D%9F"><span class="toc-text">4. PRIMARY KEY 约束</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-%E4%BD%9C%E7%94%A8"><span class="toc-text">4.1 作用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2-%E5%85%B3%E9%94%AE%E5%AD%97"><span class="toc-text">4.2 关键字</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3-%E7%89%B9%E7%82%B9"><span class="toc-text">4.3 特点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-4-%E6%B7%BB%E5%8A%A0%E4%B8%BB%E9%94%AE%E7%BA%A6%E6%9D%9F"><span class="toc-text">4.4 添加主键约束</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-5-%E5%85%B3%E4%BA%8E%E5%A4%8D%E5%90%88%E4%B8%BB%E9%94%AE"><span class="toc-text">4.5 关于复合主键</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-6-%E5%88%A0%E9%99%A4%E4%B8%BB%E9%94%AE%E7%BA%A6%E6%9D%9F"><span class="toc-text">4.6 删除主键约束</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-%E8%87%AA%E5%A2%9E%E5%88%97%EF%BC%9AAUTO-INCREMENT"><span class="toc-text">5. 自增列：AUTO_INCREMENT</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#5-1-%E4%BD%9C%E7%94%A8"><span class="toc-text">5.1 作用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-2-%E5%85%B3%E9%94%AE%E5%AD%97"><span class="toc-text">5.2 关键字</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-3-%E7%89%B9%E7%82%B9%E5%92%8C%E8%A6%81%E6%B1%82"><span class="toc-text">5.3 特点和要求</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-4-%E5%A6%82%E4%BD%95%E6%8C%87%E5%AE%9A%E8%87%AA%E5%A2%9E%E7%BA%A6%E6%9D%9F"><span class="toc-text">5.4 如何指定自增约束</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-5-%E5%A6%82%E4%BD%95%E5%88%A0%E9%99%A4%E8%87%AA%E5%A2%9E%E7%BA%A6%E6%9D%9F"><span class="toc-text">5.5 如何删除自增约束</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-6-MySQL-8-0%E6%96%B0%E7%89%B9%E6%80%A7%E2%80%94%E8%87%AA%E5%A2%9E%E5%8F%98%E9%87%8F%E7%9A%84%E6%8C%81%E4%B9%85%E5%8C%96"><span class="toc-text">5.6 MySQL 8.0新特性—自增变量的持久化</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-FOREIGN-KEY-%E7%BA%A6%E6%9D%9F"><span class="toc-text">6. FOREIGN KEY 约束</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#6-1-%E4%BD%9C%E7%94%A8"><span class="toc-text">6.1 作用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-2-%E5%85%B3%E9%94%AE%E5%AD%97"><span class="toc-text">6.2 关键字</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-3-%E4%B8%BB%E8%A1%A8%E5%92%8C%E4%BB%8E%E8%A1%A8-%E7%88%B6%E8%A1%A8%E5%92%8C%E5%AD%90%E8%A1%A8"><span class="toc-text">6.3 主表和从表&#x2F;父表和子表</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-4-%E7%89%B9%E7%82%B9"><span class="toc-text">6.4 特点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-5-%E6%B7%BB%E5%8A%A0%E5%A4%96%E9%94%AE%E7%BA%A6%E6%9D%9F"><span class="toc-text">6.5 添加外键约束</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-6-%E6%BC%94%E7%A4%BA%E9%97%AE%E9%A2%98"><span class="toc-text">6.6 演示问题</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-7-%E7%BA%A6%E6%9D%9F%E7%AD%89%E7%BA%A7"><span class="toc-text">6.7 约束等级</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-8-%E5%88%A0%E9%99%A4%E5%A4%96%E9%94%AE%E7%BA%A6%E6%9D%9F"><span class="toc-text">6.8 删除外键约束</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-9-%E5%BC%80%E5%8F%91%E5%9C%BA%E6%99%AF"><span class="toc-text">6.9 开发场景</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-10-%E9%98%BF%E9%87%8C%E5%BC%80%E5%8F%91%E8%A7%84%E8%8C%83"><span class="toc-text">6.10 阿里开发规范</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7-CHECK-%E7%BA%A6%E6%9D%9F"><span class="toc-text">7. CHECK 约束</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#7-1-%E4%BD%9C%E7%94%A8"><span class="toc-text">7.1 作用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E5%85%B3%E9%94%AE%E5%AD%97"><span class="toc-text">2、关键字</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E8%AF%B4%E6%98%8E%EF%BC%9AMySQL-5-7-%E4%B8%8D%E6%94%AF%E6%8C%81"><span class="toc-text">3、说明：MySQL 5.7 不支持</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#8-DEFAULT%E7%BA%A6%E6%9D%9F"><span class="toc-text">8. DEFAULT约束</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#8-1-%E4%BD%9C%E7%94%A8"><span class="toc-text">8.1 作用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8-2-%E5%85%B3%E9%94%AE%E5%AD%97"><span class="toc-text">8.2 关键字</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8-3-%E5%A6%82%E4%BD%95%E7%BB%99%E5%AD%97%E6%AE%B5%E5%8A%A0%E9%BB%98%E8%AE%A4%E5%80%BC"><span class="toc-text">8.3 如何给字段加默认值</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8-4-%E5%A6%82%E4%BD%95%E5%88%A0%E9%99%A4%E9%BB%98%E8%AE%A4%E5%80%BC%E7%BA%A6%E6%9D%9F"><span class="toc-text">8.4 如何删除默认值约束</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#9-%E9%9D%A2%E8%AF%95"><span class="toc-text">9. 面试</span></a></li></ol></li></ol></div></div></div></div></main><footer id="footer" style="background-color: transparent;"><div id="footer-wrap"><div id="ft"><div class="ft-item-1"><div class="t-top"><div class="t-t-l"><p class="ft-t t-l-t">格言🧬</p><div class="bg-ad"><div>再看看那个光点，它就在这里，这是家园，这是我们 —— 你所爱的每一个人，你认识的一个人，你听说过的每一个人，曾经有过的每一个人，都在它上面度过他们的一生✨</div><div class="btn-xz-box"><a class="btn-xz" target="_blank" rel="noopener" href="https://stellarium.org/">点击开启星辰之旅</a></div></div></div><div class="t-t-r"><p class="ft-t t-l-t">猜你想看💡</p><ul class="ft-links"><li><a href="/posts/eec9786.html">魔改指南</a><a href="/box/nav/">网址导航</a></li><li><a href="/social/link/">我的朋友</a><a href="/comments/">留点什么</a></li><li><a href="/personal/about/">关于作者</a><a href="/archives/">文章归档</a></li><li><a href="/categories/">文章分类</a><a href="/tags/">文章标签</a></li><li><a href="/box/Gallery/">我的画廊</a><a href="/personal/bb/">我的唠叨</a></li><li><a href="/site/time/">建设进程</a><a href="/site/census/">网站统计</a></li></ul></div></div></div><div class="ft-item-2"><p class="ft-t">推荐友链⌛</p><div class="ft-img-group"><div class="img-group-item"><a href="https://www.naste.top:1024/" title="XiaoFei🥝"><img src= "" data-lazy-src="https://www.naste.top:9000/images/cat.jpg" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div></div></div></div><div class="copyright"><span><b>&copy;2022-2024</b></span><span><b>&nbsp;&nbsp;By XiaoFei🥝</b></span></div><div id="workboard"></div><p id="ghbdages"><a class="github-badge" target="_blank" href="https://hexo.io/" style="margin-inline:5px" title="博客框架为Hexo_v6.3.0"><img src= "" data-lazy-src="https://static.naste.top:1024/svg/blog/Frame-Hexo-blue.svg" alt=""/></a><a class="github-badge" target="_blank" href="https://butterfly.js.org/" style="margin-inline:5px" title="主题版本Butterfly_v4.3.1"><img src= "" data-lazy-src="https://static.naste.top:1024/svg/blog/Theme-Butterfly-6513df.svg" alt=""/></a><a class="github-badge" target="_blank" href="https://vercel.com/" style="margin-inline:5px" title="本站采用多线部署，主线路托管于Vercel"><img src= "" data-lazy-src="https://static.naste.top:1024/svg/blog/Hosted-Vercel-brightgreen.svg" alt=""/></a><a class="github-badge" target="_blank" href="https://user.51.la/" style="margin-inline:5px" title="本站数据分析得益于51la技术支持"><img src= "" data-lazy-src="https://static.naste.top:1024/svg/blog/Analytics-51la-3db1eb.svg" alt=""/></a><a class="github-badge" target="_blank" href="https://github.com/" style="margin-inline:5px" title="本网站源码由Github提供存储仓库"><img src= "" data-lazy-src=" https://static.naste.top:1024/svg/blog/Source-Github-d021d6.svg" alt=""/></a></p></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><a class="icon-V hidden" onclick="switchNightMode()" title="浅色和深色模式转换"><svg width="25" height="25" viewBox="0 0 1024 1024"><use id="modeicon" xlink:href="#icon-moon"></use></svg></a><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button><button class="share" type="button" title="右键模式" onclick="changeMouseMode()"><i class="fas fa-mouse"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog right_side"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button class="share" type="button" title="分享链接" onclick="share()"><i class="fas fa-share-nodes"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i><span id="percent">0<span>%</span></span></button><button id="go-down" type="button" title="直达底部" onclick="btf.scrollToDest(document.body.scrollHeight, 500)"><i class="fas fa-arrow-down"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div class="js-pjax" id="rightMenu"><div class="rightMenu-group rightMenu-small"><a class="rightMenu-item" href="javascript:window.history.back();"><i class="fa fa-arrow-left"></i></a><a class="rightMenu-item" href="javascript:window.history.forward();"><i class="fa fa-arrow-right"></i></a><a class="rightMenu-item" href="javascript:window.location.reload();"><i class="fa fa-refresh"></i></a><a class="rightMenu-item" href="javascript:rmf.scrollToTop();"><i class="fa fa-arrow-up"></i></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-text"><a class="rightMenu-item" href="javascript:rmf.copySelect();"><i class="fa fa-copy"></i><span>复制</span></a><a class="rightMenu-item" href="javascript:window.open(&quot;https://www.baidu.com/s?wd=&quot;+window.getSelection().toString());window.location.reload();"><i class="fa fa-search"></i><span>百度搜索</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-too"><a class="rightMenu-item" href="javascript:window.open(window.getSelection().toString());window.location.reload();"><i class="fa fa-link"></i><span>转到链接</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-paste"><a class="rightMenu-item" href="javascript:rmf.paste()"><i class="fa fa-copy"></i><span>粘贴</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-post"><a class="rightMenu-item" href="#post-comment"><i class="fas fa-comment"></i><span>空降评论</span></a><a class="rightMenu-item" href="javascript:rmf.copyWordsLink()"><i class="fa fa-link"></i><span>复制本文地址</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-to"><a class="rightMenu-item" href="javascript:rmf.openWithNewTab()"><i class="fa fa-window-restore"></i><span>新窗口打开</span></a><a class="rightMenu-item" id="menu-too" href="javascript:rmf.open()"><i class="fa fa-link"></i><span>转到链接</span></a><a class="rightMenu-item" href="javascript:rmf.copyLink()"><i class="fa fa-copy"></i><span>复制链接</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-img"><a class="rightMenu-item" href="javascript:rmf.saveAs()"><i class="fa fa-download"></i><span>保存图片</span></a><a class="rightMenu-item" href="javascript:rmf.openWithNewTab()"><i class="fa fa-window-restore"></i><span>在新窗口打开</span></a><a class="rightMenu-item" href="javascript:rmf.copyLink()"><i class="fa fa-copy"></i><span>复制图片链接</span></a></div><div class="rightMenu-group rightMenu-line"><a class="rightMenu-item" href="javascript:randomPost()"><i class="fa fa-paper-plane"></i><span>随便逛逛</span></a><a class="rightMenu-item" href="javascript:switchNightMode();"><i class="fa fa-moon"></i><span>昼夜切换</span></a><a class="rightMenu-item" href="/personal/about/"><i class="fa fa-info-circle"></i><span>关于博客</span></a><a class="rightMenu-item" href="javascript:toggleWinbox();"><i class="fas fa-cog"></i><span>美化设置</span></a><a class="rightMenu-item" href="javascript:rmf.fullScreen();"><i class="fas fa-expand"></i><span>切换全屏</span></a><a class="rightMenu-item" href="javascript:window.print();"><i class="fa-solid fa-print"></i><span>打印页面</span></a></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.staticfile.org/fancyapps-ui/4.0.31/fancybox.umd.min.js"></script><script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/instant.page/5.1.0/instantpage.min.js" type="module"></script><script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/vanilla-lazyload/17.3.1/lazyload.iife.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdnjs.cloudflare.com/ajax/libs/pangu/4.0.7/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (true){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><script src="/js/search/local-search.js"></script><script async="async">var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())
setTimeout(function(){preloader.endLoading();}, 5000);
document.getElementById('loading-box').addEventListener('click',()=> {preloader.endLoading()})</script><div class="js-pjax"><script>(()=>{
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: '',
      region: '',
      onCommentLoaded: function () {
        btf.loadLightbox(document.querySelectorAll('#twikoo .tk-content img:not(.tk-owo-emotion)'))
      }
    }, null))
  }

  const getCount = () => {
    const countELement = document.getElementById('twikoo-count')
    if(!countELement) return
    twikoo.getCommentsCount({
      envId: '',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      countELement.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const runFn = () => {
    init()
    
  }

  const loadTwikoo = () => {
    if (typeof twikoo === 'object') {
      setTimeout(runFn,0)
      return
    } 
    getScript('https://cdn.staticfile.org/twikoo/1.6.8/twikoo.all.min.js').then(runFn)
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo()
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script src="https://cdn.staticfile.org/jquery/3.6.3/jquery.min.js"></script><script async src="https://cdn1.tianli0.top/npm/vue@2.6.14/dist/vue.min.js"></script><script async src="https://cdn1.tianli0.top/npm/element-ui@2.15.6/lib/index.js"></script><script async src="https://cdn.bootcdn.net/ajax/libs/clipboard.js/2.0.11/clipboard.min.js"></script><script defer type="text/javascript" src="https://cdn1.tianli0.top/npm/sweetalert2@8.19.0/dist/sweetalert2.all.js"></script><script async src="//npm.elemecdn.com/pace-js@1.2.4/pace.min.js"></script><script defer src="https://cdn1.tianli0.top/gh/nextapps-de/winbox/dist/winbox.bundle.min.js"></script><script async src="//at.alicdn.com/t/c/font_3586335_hsivh70x0fm.js"></script><script async src="//at.alicdn.com/t/c/font_3636804_gr02jmjr3y9.js"></script><script async src="//at.alicdn.com/t/c/font_3612150_kfv55xn3u2g.js"></script><script async src="https://cdn.wpon.cn/2022-sucai/Gold-ingot.js"></script><canvas id="universe"></canvas><canvas id="snow"></canvas><script defer src="/js/fomal.js"></script><link rel="stylesheet" href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/aplayer/1.10.1/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/aplayer/1.10.1/APlayer.min.js"></script><script src="https://cdn1.tianli0.top/npm/js-heo@1.0.12/metingjs/Meting.min.js"></script><script src="https://lib.baomitu.com/pjax/0.2.8/pjax.min.js"></script><script>let pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show","#web_bg",".js-pjax","#bibi","body > title","#app","#tag-echarts","#posts-echart","#categories-echarts"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --> <script data-pjax>if(document.getElementById('recent-posts') && (location.pathname ==='/'|| '/' ==='all')){
    var parent = document.getElementById('recent-posts');
    var child = '<div class="recent-post-item" style="width:100%;height: auto"><div id="catalog_magnet"><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/Java/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍡 XiaoFeiのJava学习笔记 (55)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/Linux/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍼 XiaoFeiのLinux笔记 (33)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/Python/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍉 XiaoFeiのPython笔记 (2)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/前端/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍟 XiaoFeiの前端笔记 (17)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/Other/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍥 XiaoFeiのOther笔记 (10)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item" style="visibility: hidden"></div><a class="magnet_link_more"  href="https://www.naste.top:1024/categories/" style="flex:1;text-align: center;margin-bottom: 10px;">查看更多...</a></div></div>';
    console.log('已挂载magnet')
    parent.insertAdjacentHTML("afterbegin",child)}
     </script><style>#catalog_magnet{flex-wrap: wrap;display: flex;width:100%;justify-content:space-between;padding: 10px 10px 0 10px;align-content: flex-start;}.magnet_item{flex-basis: calc(33.333333333333336% - 5px);background: #e9e9e9;margin-bottom: 10px;border-radius: 8px;transition: all 0.2s ease-in-out;}.magnet_item:hover{background: var(--text-bg-hover)}.magnet_link_more{color:#555}.magnet_link{color:black}.magnet_link:hover{color:white}@media screen and (max-width: 600px) {.magnet_item {flex-basis: 100%;}}.magnet_link_context{display:flex;padding: 10px;font-size:16px;transition: all 0.2s ease-in-out;}.magnet_link_context:hover{padding: 10px 20px;}</style>
    <style></style><script data-pjax>
  function butterfly_swiper_injector_config(){
    var parent_div_git = document.getElementById('recent-posts');
    var item_html = '<div class="recent-post-item" style="height: auto;width: 100%"><div class="blog-slider swiper-container-fade swiper-container-horizontal" id="swiper_container"><div class="blog-slider__wrp swiper-wrapper" style="transition-duration: 0ms;"><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;posts/204253054.html&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://www.naste.top:9000/webp/1675912191.webp" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2023-03-08</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;posts/204253054.html&quot;);" href="javascript:void(0);" alt="">SpringBoot使用实现定时任务和xxl-job实现分布式任务调度</a><div class="blog-slider__text">SpringBoot使用实现定时任务和xxl-job实现分布式任务调度</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;posts/204253054.html&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;posts/538133837.html&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://www.naste.top:9000/webp/1678672933.webp" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2023-03-15</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;posts/538133837.html&quot;);" href="javascript:void(0);" alt="">Hexo中Markdown语法与外挂标签写法汇总</a><div class="blog-slider__text">Hexo中Markdown语法与外挂标签写法汇总</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;posts/538133837.html&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div></div><div class="blog-slider__pagination swiper-pagination-clickable swiper-pagination-bullets"></div></div></div>';
    console.log('已挂载butterfly_swiper')
    parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  var elist = 'undefined'.split(',');
  var cpage = location.pathname;
  var epage = '/';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_swiper_injector_config();
  }
  else if (epage === cpage){
    butterfly_swiper_injector_config();
  }
  </script><script defer src="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper.min.js"></script><script defer data-pjax src="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper_init.js"></script><div class="js-pjax"><script async="async">var arr = document.getElementsByClassName('recent-post-item');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '2s');
    arr[i].setAttribute('data-wow-delay', '200ms');
    arr[i].setAttribute('data-wow-offset', '30');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script><script async="async">var arr = document.getElementsByClassName('card-widget');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '2s');
    arr[i].setAttribute('data-wow-delay', '200ms');
    arr[i].setAttribute('data-wow-offset', '30');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script></div><script defer src="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/wow.min.js"></script><script defer src="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/wow_init.js"></script><script data-pjax src="https://npm.elemecdn.com/hexo-filter-gitcalendar/lib/gitcalendar.js"></script><script data-pjax>
  function gitcalendar_injector_config(){
      var parent_div_git = document.getElementById('gitZone');
      var item_html = '<div class="recent-post-item" id="gitcalendarBar" style="width:100%;height:auto;padding:10px;"><style>#git_container{min-height: 320px}@media screen and (max-width:650px) {#git_container{min-height: 0px}}</style><div id="git_loading" style="width:10%;height:100%;margin:0 auto;display: block;"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 50 50" style="enable-background:new 0 0 50 50" xml:space="preserve"><path fill="#d0d0d0" d="M25.251,6.461c-10.318,0-18.683,8.365-18.683,18.683h4.068c0-8.071,6.543-14.615,14.615-14.615V6.461z" transform="rotate(275.098 25 25)"><animatetransform attributeType="xml" attributeName="transform" type="rotate" from="0 25 25" to="360 25 25" dur="0.6s" repeatCount="indefinite"></animatetransform></path></svg><style>#git_container{display: none;}</style></div><div id="git_container"></div></div>';
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
      console.log('已挂载gitcalendar')
      }

    if( document.getElementById('gitZone') && (location.pathname ==='/personal/about/'|| '/personal/about/' ==='all')){
        gitcalendar_injector_config()
        GitCalendarInit("https://gitcalendar.naste.top/api?xiao-i-fei",['#d9e0df', '#c6e0dc', '#a8dcd4', '#9adcd2', '#89ded1', '#77e0d0', '#5fdecb', '#47dcc6', '#39dcc3', '#1fdabe', '#00dab9'],'xiao-i-fei')
    }
  </script><!-- hexo injector body_end end --></body></html>